DataBinding系列(二):DataBinding的基本用法

在上一章 DataBinding系列(一):DataBinding初认识,我们已经认识了DataBinding,并且学习了它的集成方式,而这一篇就为大家带来关于它的一些基础语法。这里也给出官方文档的学习地址,我这个是国内的Android官网地址,不需要翻墙的,以后很多Android知识都可以在这里学习,建议开发者提升英语水平,否则阅读会比较吃力。
Binding学习官方文档

1.在xml中引入一些基础变量Variables

data 标签中可以有任意数量的 variable 标签。这些变量可以使Java中的任意数据类型,每个 variable 标签描述了会在 binding 表达式中使用的属性。

<layout xmlns:android="http://schemas.android.com/apk/res/android">  
    <data>  
        <variable  
            name="str"  
            type="String"/>  
        <variable  
            name="age"  
            type="int" />  
    </data>  

    <LinearLayout  
        android:orientation="vertical"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content">  
        <TextView  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:text="@{str}"/>
        <TextView  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:text="@{String.valueOf(age)}"/>  
    </LinearLayout>  
</layout>

Data Binding和Java一样,java.lang包里的类,我们是可以不用导入包的,也就是说,java基础类型都是不用导包的。注意:android:text设置int类型的值一定要转化为String类型,否则系统会认为是资源文件id,就会出错*

2.引入一些高级变量Variables

在上面,我们学会了如何在xml中定义变量,以及在控件中使用。同样,我们可以在data中定义像List、Map,数组等这样的集合变量,只是它的实现稍微有点不同,下面就一起来看看是如何定义以及使用的。

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <import type="java.util.List" />
        <import type="java.util.Map" />

        <!--泛型的支持会在编译时期报红线,但是是可以直接运行的
       但是需要通过转义字符才行,如:<号用&lt表示;>号用&gt表示;-->
       <variable
            name="list"
            type="List<String>" />

        <variable
            name="map"
            type="Map<String,Object>" />

        <variable
            name="array"
            type="String[]" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{list[0]}" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{list.get(1)}" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="@{map[`key0`]}" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{map.get(`key1`)}" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="@{array[0]}" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{array[1]}" />

    </LinearLayout>
</layout>   

大家可以看到,list和map这里我没有用List<String>和Map<String,Object>,而是用的List<String>和Map<String,Object>原因是在data中,有些字符是必须用转义字符才能编译通过,上面把<>换成转义字符的写法虽然会在编译时是红色的,但是不用担心,会编译通过的,下面给出常用的转义字符。

附:常用的转义字符

显示结果 描述 转义字符 十进制
空格 &nbsp; &#160;
< 小于号 &lt; &#60;
> 大于号 &gt; &#62;
& 与号 &amp; &#38;
" 引号 &quot; &#34;
撇号 &apos; &#39;
× 乘号 &times; &#215;
÷ 除号 &divide; &#247;

关于获取list和map的值,我们有2种写法,[]或者是get(),如果是list或者数组,需要设置索引下标,如果是map,还需要为它定义key的变量,官方推荐这种集合框架使用[]的写法。

注意: android:text=""这里,我用的是双引号的写法,官方还有一种单引号的写法。

单引号
官方说单引号比双引号更容易使用

android:text='@{map["key0"]}'

双引号
双引号当然也是可以的,只是你的key要用``包裹,注意,这个不是单引号,而是Tab键上面的那个键的那个点。

在Activity中初始化数据,设置这些变量

public class BasicActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityBasicBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_basic);

        List<String> list = new ArrayList<>();
        list.add("list1");
        list.add("list2");
        binding.setList(list);

        HashMap<String, Object> map = new HashMap<>();
        map.put("key0", "map_value0");
        map.put("key1", "map_value1");
        binding.setMap(map);
        
        String[] arrays = {"字符串1", "字符串2"};
        binding.setArray(arrays);
    }
}

3.xml中引用表达式

举几个例子,还有很多,大多数Java表达式都是支持的

android:text="@{String.valueOf(age)}"
android:visibility="@{age < 13 ? View.GONE : View.VISIBLE}"
android:text='@{"iname:" +user.name}'

此外还支持null合并操作,它的符号是??,意思是:如果左边的对象非空则选择左边,否则选择右边,这和Java中的三目运算符是一样的,可以算是一个简略吧。

android:text="@{user.displayName ?? user.lastName}"
//等价于
android:text="@{user.displayName != null ? user.displayName : user.lastName}"

支持的表达式语言
表达式语言与 Java 表达式有很多相似之处。下面是相同之处:

  • 数学计算 + - / * %
  • 字符串连接 +
  • 逻辑 && ||
  • 二进制 & | ^
  • 一元 + - ! ~
  • 位移 >> >>> <<
  • 比较 == > < >= <=
  • instanceof
  • 组 ()
  • 字面量 - 字符,字符串,数字, null
  • 类型转换
  • 函数调用
  • 字段存取
  • 数组存取 []
  • 三元运算符 ?:

不支持的操作符
一些 Java 中的操作符在表达式语法中不能使用。

  • this
  • super
  • new
  • 显式泛型调用 <T>

4.设置别名alias

如果我们import了两个不同路径,但名称相同的类,可以借助于别名来解决,别名借助alias字段来标识,例如:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <import type="com.zx.databindingdemo.bean.UserBean" />
        <!--不同路径下有2个相同名字的类,那么给其中一个起一个别名,用alias表示-->
       <import type="com.zx.databindingdemo.bean.user.UserBean" alias="UserBean2"/>

        <variable
            name="user"
            type="UserBean" />
        
        <variable 
            name="user2" 
            type="UserBean2"/>
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="@{`姓名:`+user.name}" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="@{`user2:`+user2.content}" />
      
    </LinearLayout>
</layout>   

在Activity中

public class BasicActivity extends AppCompatActivity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityBasicBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_basic);

        UserBean userBean = new UserBean(URL_USER_PIC, "张三", 24);
        binding.setUser(userBean);

        com.zx.databindingdemo.bean.user.UserBean userBean2 = new com.zx.databindingdemo.bean.user.UserBean("我是user2");
        binding.setUser2(userBean2);
    }

5.include中的使用

在使用命名空间的布局中,变量可以传递到任何 include 布局中。

<?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>
       <variable name="user" type="com.example.User"/>
   </data>
   <LinearLayout
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <include layout="@layout/name"
          app:user="@{user}"/>
       <include layout="@layout/contact"
          app:user="@{user}"/>
   </LinearLayout>
</layout>

注意:在name.xml以及contact.xml两个layout文件中必需要有user variable

Data binding不支持直接包含merge 节点。举个例子, 以下的代码不能正常运行 :

<?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>
       <variable name="user" type="com.example.User"/>
   </data>
   <merge>
       <include layout="@layout/name"
        app:user="@{user}"/>
       <include layout="@layout/contact"
         app:user="@{user}"/>
   </merge>
</layout>

6.事件处理

大家都知道,我们经常需要处理View的点击事件,在xml中android:onClick 可以指定 Activity 中的函数,Data Binding 也允许处理从视图中发送的事件。

下面给出几种实现方式:

  • 布局中引入OnClickListener的变量
  • 方法调用

布局中引入OnClickListener的变量

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <variable
            name="clickListener"
            type="android.view.View.OnClickListener" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:orientation="vertical">

        <Button
            android:id="@+id/click_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="@{clickListener}"
            android:text="点我" />

        <Button
            android:id="@+id/click2_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="@{clickListener}"
            android:text="点我2" />

    </LinearLayout>
</layout>   

Activity处理点击事件

public class BasicActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityBasicBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_basic);
        
        binding.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.click_btn) {
            Toast.makeText(this, "点击了1", Toast.LENGTH_SHORT).show();
        } else if (v.getId() == R.id.click2_btn) {
            Toast.makeText(this, "点击了2", Toast.LENGTH_SHORT).show();
        }
    }
}

方法调用
相比较于在android:onClick中指定Activity的一个方法,它的优势在于表达式会在编译时处理,如果方法不存在或者方法签名不对,编译将会报错。
以下是个例子:

public class OnClickHandler {
    public void onClickFriend(View view) {
        Toast.makeText(view.getContext(), "onClickFriend", Toast.LENGTH_SHORT).show();
    }
}

布局文件如下

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
         <variable
            name="handler"
            type="com.zx.databindingdemo.handler.OnClickHandler" />
    </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="@{handler::onClickFriend}"/>
        <!-- 注意:函数名和监听器对象必须对应 -->
        <!-- 函数调用也可以使用 `.` , 如handler.onClickFriend , 不过已弃用 -->
    </LinearLayout>
</layout>

别忘了在Activity设置变量

binding.setHandler(new OnClickHandler());

github源码下载

欢迎学习交流这个系列的文章
DataBinding系列(一):DataBinding初认识
DataBinding系列(三):RecyclerView中使用DataBinding
DataBinding系列(四):DataBinding进阶之路

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容