为什么推荐你使用ViewBinding 替换findViewById 和 ButterKnife ? 因为太爽了,太上头了。 用过一次就爱上了,再也不想回去。真心的。不信你看下文!
定义
ViewBinding 是google推出Jetpack库的一个组件,主要用于视图绑定,替代 findViewById操作.Viewbinding会根据xml文件生成一个对应的绑定类, 比如我们xml文件是: activity_login_layout.xml 生成的绑定类就是ActivityLoginLayoutBinding 这么一个类.在使用的时候直接通过生成的绑定类调用我们xml中的视图组件, 不用findViewById,也不用声明组件. 接下来看下我们集成和项目就能很快的理解.
集成
首先在我们工程build.gradld中引入viewBind
//引入ViewBinding
viewBinding {
viewBinding = true
}
然后我们就可以在代码中使用ViewBinding了
代码
创建了一个登录页面, activity_login_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
tools:viewBindingIgnore="false"
android:padding="16dp">
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/tv_login_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="登录"
android:textColor="@color/design_default_color_primary_variant"
android:textSize="19sp" />
<androidx.appcompat.widget.AppCompatEditText
android:id="@+id/et_login_account"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:hint="用户名"
android:paddingStart="10dp"
android:paddingEnd="10dp" />
<androidx.appcompat.widget.AppCompatEditText
android:id="@+id/et_login_pwd"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:hint="密码"
android:paddingStart="10dp"
android:paddingEnd="10dp" />
<Button
android:id="@+id/btn_login"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="20dp"
android:background="@color/design_default_color_secondary"
android:text="登录"
android:textSize="20dp" />
<TextView
android:id="@+id/tv_find_pwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:text="找回密码"
android:textColor="@android:color/holo_red_dark"
android:textSize="16sp" />
</LinearLayout>