ViewBinding是通过视图绑定,给每个xml文件生成一个类,通过这个类,我们可以直接获得控件对象,不需要再findViewById。
与DataBinding相比,ViewBinding更加轻量,速度更快,再比较简单的项目开发时,用起来很方便。同时ViewBinding编译安全,不会像ButterKnife或者Kotlin Android Extensions一样,能够拿到其他xml文件中的控件id,这样容易带来一些粗心导致的错误。
ViewBinding使用
第一步 开启ViewBinding
android{
...
buildFeatures {
viewBinding true
}
}
第二步 新建布局文件
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
第三步 在Activity中直接使用
class ViewBindingActivity : AppCompatActivity() {
lateinit var mBinding: ActivityViewBindingBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding= ActivityViewBindingBinding.inflate(layoutInflater)
setContentView(mBinding.root)
mBinding.tv1.text = "aaa"
}
}