Android架构组件–ViewBinding学习笔记
1.解决的问题
ViewBinding
的目的是为了减少样板代码findViewById(int)
的使用,提升开发效率,精简Activity
和Fragment
的代码。
2.使用ViewBinding
ViewBinding
的使用需要Android Studio
版本为3.6以上,需要在模块的build.gradle
文件中手动开启,如下:
android {
...
buildFeatures {
viewBinding = true
}
}
之后Android Studio
会自动为layout
文件夹下的布局文件生成对应的Java
类,命名规则为文件名的大驼峰命名并在后面加上Binding
。
比如activity_main.xml
布局文件如下:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/timestampText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="@color/colorPrimary"
android:gravity="center"
android:padding="20dp"
tools:text="Hello world"
app:layout_constraintTop_toTopOf="parent"/>
<Button
android:id="@+id/timestampButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraint