0
0

More than 3 years have passed since last update.

【Kotlin 初心者】bindingでidを取得する方法

Last updated at Posted at 2021-03-18

bindingでidを取得する方法

Kotlinでxmlのidを取得する際にfindViewByIdを使ってないですか?
findViewByIdよりもbindingならidの取得が楽になります

  • アプリのbudild.gradleをにViewBindingをtrueにします
build.gradle

android {
 viewBinding {
      enabled = true
   }
}
  • bindingを初期化
MainActivity.kt

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

   override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // bindingを初期化します
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

   }
}
  • ここまでできたらbindingの準備は完了です
MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        // Buttonのidを取得
     binding.button

       // findViewByIdでButtonのidを取得
       val button = findViewById<Button>(R.id.button)
}

bindingとfindViewByIdを比較するとわかりやすいかと思います
これでidの取得がとても楽になりますね

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