開(kāi)啟ViewBinding粥庄,只需在app -> build.gradle中增加一下配置
android {
...
buildFeatures {
viewBinding true
}
}
ViewBinding會(huì)在編譯期根據(jù)layout文件生成對(duì)應(yīng)的class仗考,如:first_layout.xml苛败,會(huì)生成FirstLayoutBinding的class创肥。
在A(yíng)ctivity中創(chuàng)建ViewBinding實(shí)例改备, 并在適當(dāng)?shù)臅r(shí)候訪(fǎng)問(wèn)其成員
import com.example.activitytest.databinding.FirstLayoutBinding
class FirstActivity : AppCompatActivity() {
private lateinit var binding: FirstLayoutBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = FirstLayoutBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
binding.button1.setOnClickListener {
Toast.makeText(this, "You clicked Button ", Toast.LENGTH_SHORT).show()
}
}
}