DataBinding系列:DataBinding的基本用法

转载自:https://www.jianshu.com/p/70316eb4e0f8

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&lt;String&gt;" />

        <variable
            name="map"
            type="Map&lt;String,Object&gt;" />

        <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>   

踩坑:

1、目前遇到as环境中,在xml中Map必须使用泛型,List可以不使用,否则编译报错;

2、在xml中使用泛型,不能写<>,只能使用转义字符,否则报错,应如下Map&lt;String,Object&gt;

附:常用的转义字符

显示结果 描述 转义字符 十进制
  空格 &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

<?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:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{`我的名字`+user.name}"/>
    </LinearLayout>

</layout>

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());

猜你喜欢

转载自blog.csdn.net/qq_35559358/article/details/83589544