android kotlin viewBinding 新做法

寫android總是寫不好, 之前取得view要使用findViewByI的方式, 過了一段時間回頭看, 現在又改了改成使用viewBinding 說是比較快…

  • gradle(module)
buildFeatures {
    viewBinding = true
}
  • main activity
class MainActivity : AppCompatActivity() {

    lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }
}
  • 使用方式變簡單了
// 舊版
val myButton: Button = findViewById(R.id.my_button)
myButton.text = "A button"

// 新版
val myButton: Button = binding.myButton
myButton.text = "A button"

// Best way with view binding and no extra variable
binding.myButton.text = "A button"

發表迴響