kotlinxを使ってViewを操作しようとすると、実行に失敗する - d-sazanami/highandlow GitHub Wiki

現象

ハロー・ワールド・アプリではgradle設定を変更するだけで、書籍の通りkotlinxを使うことができたが、新しくプロジェクトを作って、ビルドすると何か失敗した。

ビルド時のログ

> Configure project :app
Warning: The 'kotlin-android-extensions' Gradle plugin is deprecated. Please use this migration guide (https://goo.gle/kotlin-android-extensions-deprecation) to start working with View Binding (https://developer.android.com/topic/libraries/view-binding) and the 'kotlin-parcelize' plugin.
Checking the license for package Android SDK Build-Tools 30.0.2 in C:\Users\{ユーザー名}\AppData\Local\Android\Sdk\licenses
Warning: License for package Android SDK Build-Tools 30.0.2 not accepted.
Checking the license for package Android SDK Platform 30 in C:\Users\lukif\AppData\Local\Android\Sdk\licenses
Warning: License for package Android SDK Platform 30 not accepted.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/7.0.2/userguide/command_line_interface.html#sec:command_line_warnings

ビューバインディング(https://developer.android.com/topic/libraries/view-binding?hl=ja)を使えということらしい

ビューバインディングを使う

日本語化もされている公式ドキュメントの内容そのまま

1. gradleの設定でviewBindingを有効にする

Gradle Scripts > モジュールのbuild.gradleに設定する。 android { compileSdk 30 …(略)… viewBinding { enabled = true } }

android-studio_gradle-sync-now

「Sync Now」を押してしばらく待つ。

この表示が出ればOK android-studio_gradle-sync-now-success

2. ktソース上でfindViewByIdのようなことをする

packagecom.example.app

importandroidx.appcompat.app.AppCompatActivity
importandroid.os.Bundle
importcom.example.app.databinding.ActivityMainBinding


class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
      // main.activity.xmlレイアウトをバインドするために、キャメルケースBinfingの命名規則でオブジェクトを呼び、そのオブジェクトのinflateメソッドでバインディングオブジェクトを取得
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)

        // main_activity.xml中のandroid:id="@+id/hightBtn"ボタンにクリックリスナー設定
        binding.hightBtn.setOnClickListener{
        }
}

binding変数はクラス・プロパティで設定しているので、binding.{id名}でどのメソッドからもViewにアクセスできる