先在app
级别的build.gradle
中启用ViewBinding
1 2 3 4 5 6 7
| android { ... buildFeatures { viewBinding true } }
|
ViewBinding
启用后,编译项目,在build\generated\data_binding_base_class_source_out
生成各个layout
对应的Binding
类,Binding
类的命名规则为Layout
的名字换成大驼峰式写法,并且在尾部加上Binding
,默认会给每个layout
生成对应的Binding
类,如果某个layout
不需要生成,可以在layout
的根节点加上tools:viewBindingIgnore="true"
属性
1 2 3 4 5 6
| <androidx.constraintlayout.widget.ConstraintLayout ... tools:viewBindingIgnore="true" ...>
</androidx.constraintlayout.widget.ConstraintLayout>
|
创建MainActivity
,布局文件为activity_main.xml
,将会生成对应的MainActivityBinding
类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <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">
<Button android:id="@+id/button1" android:text="Button1" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toStartOf="@id/button2"/>
<Button android:id="@+id/button2" android:text="Button2" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintTop_toTopOf="@id/button1" app:layout_constraintTop_toBottomOf="@id/button1" app:layout_constraintStart_toEndOf="@id/button1" app:layout_constraintEnd_toEndOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
|
在MainActivity
中使用ViewBinding
,首先声明binding
变量
1 2
| private lateinit var binding: ActivityMainBinding
|
然后在onCreate
方法中,在setContentView
方法之前,调用ActivityMainBinding.inflate
方法,将布局文件加载到binding
变量中,再调用setContentView
方法,将binding
变量中的根视图设置为当前活动的内容视图
1 2 3 4 5 6 7
| override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) }
|
现在即可在MainActivity
中使用binding
变量来访问布局文件中的视图,例如binding.button1
和binding.button2
1 2 3 4 5 6 7
| binding.button1.setOnClickListener { Toast.makeText(this, "按钮1", Toast.LENGTH_SHORT).show() }
binding.button2.setOnClickListener { Toast.makeText(this, "按钮2", Toast.LENGTH_SHORT).show() }
|