赞
踩
各位看官们,大家好,上一回中咱们说的是UI框架的例子,这一回中咱们介绍的例子是视图绑定-ViewBinding。闲话休提,言归正转,让我们一起Talk Android吧!
看官们,我们说的视图绑定就是指系统自动给xml格式的布局文件生成一个同名的视图绑定类,绑定类的对象(实例)包含布局文件中所有控件。从面向对象的角度看,绑定类是对布局的封装,布局中的控件就是绑定类的属性(成员变量)。
视图绑定功能主要用来代替findViewById()
方法,因此通过视图绑定功能,我们可以更加方便地编写与视图交互的代码。顺便说一下,在官方推出此功能之前我们可以使用butterknife,不过这个库在Android官方推出ViewBinding
功能后已经停止更新了,而且库的作者也推荐大家使用ViewBinding
.
明白概念后我对一些细节做补充:
activity_main.xml
为布局文件名,生成的绑定类名为ActivityMainBinding
;<LinearLayout
...
tools:viewBindingIgnore="true" >
</LinearLayout>
id_button_search
,属性名是IdButtonSearch
;明白视图绑定的概念后,我们通过文字结合代码的方式来介绍如何使用视图绑定功能。
android {
...
viewBinding {
enabled = true
}
}
注意:布局文件中的UI组件一定要有id,没有ID的组件无法获取到
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/id_tv_view_bind_title"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<Button
android:id="@+id/id_bt_view_bind_button"
android:layout_gravity="center"
android:text="Change Text"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
</LinearLayout>
private ActivityViewBindingExBinding mViewBinder;
mViewBinder = ActivityViewBindingExBinding.inflate(getLayoutInflater());
mView = mViewBinder.getRoot(); //获取根视图
setContentView(mView);//布局和代码绑定
注意:布局中UI组件的名称就是组件的id,只不过把分隔字母的下划线换成了大写字母;
//使用ViewBinding对象获取布局中的Button组件然后添加监听器
mViewBinder.idBtViewBindButton.setOnClickListener(v -> changeText());
private void changeText() {
//使用ViewBinding对象获取布局中的TextVeiw组件然后修改显示文本
mViewBinder.idTvViewBindTitle.setText("Text is changed!");
}
使用视图绑定可以替代 findViewById()
方法,不过它们之间还是有一些差别:
Null 安全:
视频绑定类是在编译时生成的,如果布局中有无效的控件 ID会提前发现,不会在程序运行时因为无效的控件ID而发生 Null指针异常;
类型安全:
视图绑定类中的属性类型与它们在 XML布局文件中引用的视图类型完全相同,我们不需要做强制的类转换,进而避免因为强制类型转换而引起的异常;
看官们,关于Android中视图绑定-ViewBinding的例子咱们就介绍到这里,欲知后面还有什么例子,且听下回分解!
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。