0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Kotlinxがインポートできない問題の解決策

Last updated at Posted at 2022-01-18

概要

参考書に従ってAndroidStudioでアプリ開発を始めたところ、最初のライブラリ導入で躓きました。いろいろ調べてみて、初心者には難しいお話が多かったので解決策を置いておきます。

環境
Android Studio Arctic Fox | 2020.3.1 Patch 4

問題

スクリーンショット (15).png
明らかに有効じゃないですね。コード内で使うこともできませんでした。

解決策

Kotlinxは非推奨になり、2021年9月以降削除予定(すでに削除済みかも)です。ViewBindingに移行しましょう。

1、ViewBindingを導入

スクリーンショット (16).png

build.gradle(:appの方)を開き、android{}内に

buildFeatures {
        viewBinding true
    }

を記述。上の方に黄色いバーが出てくるので、忘れずにSync Now しておきます。これで使えるようになりました。

MainActivity.ktの編集

デフォルトのMainActivity.ktに追記します。

package com.example.hoge.outofbussinesscards

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
//以下追記
import com.example.hoge.outofbussinesscards.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    
    //以下追記
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        //以下追記
        binding = ActivityMainBinding.inflate(layoutInflater)
        //変更
        setContentView(binding.root)

    }
}

書き換え方

Kotlinxの場合

hogeBtn.setOnClickListener{

View Bindingの場合

binding.hogeBtn.setOnClickListener{

頭にbindingをつけるだけです。入力して赤文字になったらとりあえずbindingをつけてみる。

参考記事

大変お世話になりました。ありがとうございます。
参照日:2022/01/18
https://www.usaco-pg.com/2021/04/29/kotlin-android-viewbinding/#settings

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?