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の取得がとても楽になりますね