DataBinding:开启数据绑定
记得上大学的那会自学接触过Android,看Android Mars录制的安卓编程视频(网上很火的),印象最深的就是不停的敲findViewById()。现在2020年了还在用findViewById()吗?
1、何为DataBinding?
参考Android Developers > Guides > Data Binding Library。在此之前相信开发者已经写过无数次的findViewById():
TextView title = findViewById(R.id.title);
ImageView newsImage = findViewById(R.id.picture);
TextView author = findViewById(R.id.author);
TextView category = findViewById(R.id.category);
TextView date = findViewById(R.id.date);
Button deleteBtn = findViewById(R.id.delete);
....
开始使用DataBinding吧,从重复的劳动中解放出来。
1.1、DataBinding介绍
DataBinding是Jetpack中的支持库,借助该库,可以使用声明性格式(而非程序化地)将布局中的界面组件绑定到应用中的数据源,降低布局和逻辑的耦合性,使代码逻辑更加清晰。
DataBinding推出至今也有五年时间了,可是知道的人不多,用的项目就更少了。而且Google的Jetpack组件库还在不断的推出新东西,DataBinding还没过时,又出来个ViewBinding。
1.2、DataBinding的优势
DataBinding数据绑定为MVVM架构而生,优势不言而喻。除了能够减少代码中重复冗余的findViewById,还能:
①移除Activity中的许多界面框架调用
②维护起来更简单方便。
③提高应用性能
④防止内存泄漏
⑤避免发生Null指针异常
2、切换到DataBinding
2.1、启用DataBinding
要启用数据绑定,在模块的build.gradle文件中将dataBinding构建选项设置为true即可:
android {
...
buildFeatures {
dataBinding true
}
}
另一种形式的写法:
android {
...
//启用DataBinding
dataBinding {
enabled = true
}
}
Kotlin项目开启DataBinding参考Migrate from Kotlin synthetics to Jetpack view binding。既有Kotlin + Java的混合项目坑太多,各种问题。
2.2、修改XML布局
在使用DataBinding之前我们使用的XML布局大都以ViewGroup类型作为根标签:
<?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">
....
</LinearLayout>
项目中开启DataBinding后,需要稍微改变一下布局,DataBinding布局文件略有不同,以根标记<layout/>开头,后跟<data />元素和 view布局根元素。
如何将布局文件转换成支持DataBinding的布局文件呢?按住Alt + Enter见弹出下面的菜单,选择 Convert to data binding layout选项:
或者鼠标放在根布局标签处,右键菜单 > Show Context Actions打开上面的菜单:
转换后的布局文件格式如下:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
//数据
</data>
//原来的布局根标签整个被移动到这里,成为<layout>的子标签
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
</layout>
好了,到这里就已经开启DataBinding之路,继续学习DataBinding的数据绑定语法。
参考资料:
Jetpack > Libraries > Databinding
Android Developers > Guides > Data Binding Library
GitHub/Android/Databinding Code Sample
Data Binding:Get started