本文已参与「新人创作礼」活动,一起开启掘金创作之路。
DataBinding
DataBinding顾名思义就是数据绑定,即将数据绑定到UI布局 另不需再使用findViewById()即可获取控件,非常方便;当然kotlin中获取控件更方便...
使用方式
-
module的build.gradle中配置如下
android { ... dataBinding { enabled = true } }
-
布局中添加<layout>根标签和<data>标签
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <data /> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/cl_root" android:layout_width="match_parent" android:layout_height="match_parent"> ... </androidx.constraintlayout.widget.ConstraintLayout> </layout>
-
java中实例化,若布局为xxx_yyy.xml则对应的Databinding为XxxYyyBinding
// activity的onCreate()方法中 DataBindingUtil.setContentView(this, R.layout.activity_test);
// fragment的onCreateView()方法中 DataBindingUtil.inflate(Objects.requireNonNull(inflater), fragment_test, container, false);
// adapter的onCreateViewHolder()方法中 DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), adapter_test, parent, false);
-
代码获取控件方式,驼峰式(如控件id为bt_close_page则获取方式为mBinding.btClosePage)
mBinding.clRoot.setVisible(View.VISIBLE);
使用DataBinding绑定数据至布局
绑定自定义的对象数据
-
定义数据对象User类
import androidx.annotation.NonNull; public class User { private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @NonNull @Override public String toString() { return name + " -- " + age; } }
-
布局中使用<variable>声明user对象
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:bind="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"> <data> <variable name="user" type="viewmodel.User" /> ... </data> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> ... </layout>
-
布局控件中使用引进来的user数据
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="user info" android:text='@{String.format("当前用户name和age分别为:%s", user.toString)}' /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="@{user.age > 17}" android:text="年龄大于17吗" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="年龄大于17不显示该TextView" android:visibility="@{user.age > 17 ? View.GONE : View.VISIBLE}" /> </LinearLayout>
因为使用了系统api View所以需要<import>声明
<data> <import type="android.view.View" /> ... </data>
-
java中创建user实例并使用DataBinding将数据绑定至布局,并且每次更新user信息后再使用mBinding.setUser(user)将数据绑定至布局中,界面会同步更新user信息
User user = new User("ashe", 17); mBinding.setUser(user);
绑定Pair数据
-
定义数据对象Pair类,因为是系统api所以不需要定义了
-
布局中使用<variable>声明pair对象
<variable name="pair" type="Pair<String, Integer>" />
要使 XML 不含语法错误,必须转义 < 字符。例如:不要写成 List<String> 形式,而是必须写成 List<String>
-
布局控件中使用引进来的pair数据
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@{pair.first + '-' + pair.second}" />
因为使用了系统api Pair所以需要<import>声明
<import type="android.util.Pair" />
-
java中创建pair实例并使用DataBinding将数据绑定至布局,并且每次更新pair信息后再使用mBinding.setPair(pair)将数据绑定至布局中,界面会同步更新pair信息
Pair pair = new Pair<String, Integer>("akali", 25); mBinding.setPair(pair);
表达式语言
在布局的表达式中可以使用以下运算符和关键字
- 算术运算符 + - / * %
- 字符串连接运算符 +
- 逻辑运算符 && ||
- 二元运算符 & | ^
- 一元运算符 + - ! ~
- 移位运算符 >> >>> <<
- 比较运算符 == > < >= <=(请注意,< 需要转义为 <)
- instanceof
- 分组运算符 ()
- 字面量运算符 - 字符、字符串、数字、null
- 类型转换
- 方法调用
- 字段访问
- 数组访问 []
- 三元运算符 ?:
布局表达式可避免null指针异常
如表达式@{user.name}中user为null,name为String,则user.name的值为null
如表达式@{user.age}中user为null,age为int,则user.age的值为0
null合并运算符 ??
-
若左边不为null则使用左边表达式的值,否则使用右边表达式的值,下面两种方式等效
android:text="@{user.displayName ?? user.lastName}"
android:text="@{user.displayName != null ? user.displayName : user.lastName}"
属性引用
-
表达式可使用.引用属性,对于字段、getter和ObservableField对象使用方式相同
android:text="@{user.lastName}"
集合
-
可使用 [] 运算符访问常见集合,例如数组、列表、稀疏列表和映射,注意 < 需要转义为 <
<data> <import type="android.util.SparseArray"/> <import type="java.util.Map"/> <import type="java.util.List"/> <variable name="list" type="List<String>"/> <variable name="sparse" type="SparseArray<String>"/> <variable name="map" type="Map<String, String>"/> <variable name="index" type="int"/> <variable name="key" type="String"/> </data> … android:text="@{list[index]}" … android:text="@{sparse[index]}" … android:text="@{map[key]}" // 上面可下成如下方式 android:text="@{map.key}"
字符串字面量
-
下面两种方式等效
android:text='@{map["firstName"]}'
android:text="@{map[`firstName`]}"
资源
-
示例
android:padding="@{large? @dimen/largePadding : @dimen/smallPadding}"
别名alias
-
引入重复类名时可以使用别名
<import type="android.view.View"/> <import type="cc.catface.View" alias="cview"/>
包含bind
-
父布局
<include layout="@layout/activity_test_vm_i" bind:user="@{user}" />
-
被<include>的子布局
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <variable name="user" type="viewmodel.User" /> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@{user.toString()}" /> </LinearLayout> </layout>
-
不支持被merge的子布局
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:bind="http://schemas.android.com/apk/res-auto"> <data> <variable name="user" type="com.example.User"/> </data> <merge><!-- Doesn't work --> <include layout="@layout/name" bind:user="@{user}"/> <include layout="@layout/contact" bind:user="@{user}"/> </merge> </layout>
事件处理
-
定义好的事件处理类
import android.util.Log; import android.view.View; public class Actions { public void onClick(View view, User user) { Log.d("catface", getClass().getName() + "-->onClick: " + view + " || " + user.toString()); } }
-
布局中调用事件处理类
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:bind="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"> <data> <variable name="user" type="viewmodel.User" /> <variable name="actions" type="viewmodel.Actions" /> ... </data> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="@{v -> actions.onClick(v, user)}" android:text="test actions" /> ... </LinearLayout> </layout>
-
代码中绑定事件处理类至布局中
mBinding.setActions(new Actions());
-
补充:void可作为符号,示例如下
android:onClick="@{(v) -> v.isVisible() ? doSomething() : void}"