当前位置:   article > 正文

DataBinding学习(一)_android databinding 使用控件爆红

android databinding 使用控件爆红

1 引言

DataBinding,即数据绑定,可使用MVVM(Model-View-ViewModel)模式,让项目结构清晰明了。通过ViewModel连接View和Model,使得View与Model层解耦,分层后各司其职,维护方便。


2 配置环境

使用DataBinding需要引用第三方的Library。在Android Studio中,可以在build.gradle(Moudle:app)中,在android{…}中添加如下的代码:

android {
    ....
    dataBinding {
        enabled = true
    }//放在前面也是可以的
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

同步之,即可完成DataBind的环境配置。


3 绑定属性

1 绑定Bean类的属性

首先先有一个Bean类:

package com.example.ethan.databinding;//后续有用

/**
 * Created by Ethan on 2016/3/15.
 */
public class User {//private属性也一样。但需要get/set方法
    public String name;
    public String phone;
    public boolean isShow;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

修改Layout.XML文件:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
   <data>
      <variable
        name="user"//代表Bean类实例
        type="com.example.ethan.databinding.User"//Bean类的完整路径
        />
   </data>
   <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">
      <TextView
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:layout_weight="1"
        android:background="#0ff"
        android:text="@{user.name}"//若Bean类属性为private,用get方法获取
        android:textAlignment="center"/>
   </LinearLayout>
</layout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

从上面可以看出DataBinding的布局文件不同于以前的,它是以layout作为根节点data作为绑定数据的节点。
在布局文件中,可以看出DataBinding的语法格式@{ 实例.属性 }。
如果需要绑定同一个Bean类的多个实例,可以修改data中的内容为:

<import
     alias="MyUser"//当你不同包中导入相同类名就可以使用这个属性设置别名
     type="com.example.ethan.databinding.User"/>
<variable
     name="user"
     type="MyUser"/>//上面使用的别名
<!--如果需要多个对象可如下进行添加实例-->
<variable
     name="user1"
     type="MyUser"/>//上面使用的别名
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

再来看看MainActivity中的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //ActivityMainBinding这个的名是根据布局文件名自动生成的类
    ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    User user = new User();
    user.name="Tom";
    user.phone="123456";
    user.isShow=true;
    binding.setUser(user);//设置绑定
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

这样最简单的Bean类属性绑定就完成了。 有人说,如果我没设定属性值,而在XML文件中引用了会不会报错呢?这个问题的答案可以在后面的进阶用法中寻找答案~
在官网文档中有这么一句话需要注意:

If you are using data binding items inside a ListView or RecyclerView adapter, you may prefer to use:

ListItemBinding binding = ListItemBinding.inflate(layoutInflater, viewGroup, false);
//or
ListItemBinding binding = DataBindingUtil.inflate(layoutInflater, R.layout.list_item, viewGroup, false);
  • 1
  • 2
  • 3

2 绑定自定义属性

自定义属性的绑定只要2步即可。因为java.lang.* 包中的类会被自动导入,可以直接使用。

第一步:在XML文件中添加自定义属性:

<variable
    name="gender"
    type="String"/>
  • 1
  • 2
  • 3

第二步:在MainActivity中绑定所需的值。

binding.setGender("Male");//在XML文件绑定时内部自动生成了get/set方法。
  • 1

4 进阶用法

1 控制控件的显示与否

<TextView
    android:text="@{user.lastName}"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="@{user.isShow ? View.VISIBLE : View.GONE}"/>
  • 1
  • 2
  • 3
  • 4
  • 5

上面的最后一句会报红,无视之。同时需要在data中导包:

<import type="android.view.View"/>
  • 1

2 集合的使用

此处仅演示List。
XML布局文件:

<import type="java.util.ArrayList"/>//不要想着多态了==
<!--演示简单的用法,复杂的大家可以自己have a try-->
    <variable
        name="list"
        type="ArrayList&lt;String>"/>//你问我里面的"&lt;"是什么鬼?其实就是"<"。为什么这么写?你可以试试,不然我也不想!!!
    ...
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:layout_weight="1"
        android:background="#f00"
        android:text="@{list[1]}"//注意一下这个的取值方式,而且是从0开始的
        android:textAlignment="center"/>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

MainActivity文件:

ArrayList<String> list = new ArrayList<String>() {
        {
            add("arraylist");
            add("ABCD");
        }
    };
binding.setList(list);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

下面来总结下ArrayListMap的取值方式:

…
android:text="@{list[index]}"//通过索引获取,从0开始计算
…
android:text="@{array[index]}"//同上。
…
android:text="@{map[key]}"//通过key键获取值value
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

关于Map的取值可以看下下面2种可行的方式:

android:text='@{map["firstName"]}'
android:text="@{map[`firstName`}"
android:text="@{map[&quot;firstName&quot;]}"//里面转义的其实就是双引号,但不能直接填双引号
  • 1
  • 2
  • 3

3 Null Coalescing 运算符

android:text="@{user.displayName ?? user.lastName}"
  • 1

相当于

android:text="@{user.displayName != null ? user.displayName : user.lastName}"
  • 1

4 运算符的应用

Java中的诸多运算符在这也是一样适用的。

Mathematical + - / * %
String concatenation +
Logical && ||
Binary & | ^
Unary + - ! ~
Shift >> >>> <<
Comparison == > < >= <=
instanceof
Grouping ()
Literals - character, String, numeric, null
Cast
Method calls
Field access
Array access []
Ternary operator ?:
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

而以下几个则无法使用:

this
super
new 
  • 1
  • 2
  • 3

5 自动避免了空指针

看官方文档说明:

Generated data binding code automatically checks for nulls and avoid null pointer exceptions. For example, in the expression @{user.name}, if user is null, user.name will be assigned its default value (null). If you were referencing user.age, where age is an int, then it would default to 0.


6 资源文件属性获取

android:padding="@{large? @dimen/largePadding : @dimen/smallPadding}"
  • 1

4 最后

关于属性的绑定就说到这里,后续将介绍DataBinding的其他用法。

In the end,附上官网链接:http://developer.android.com/tools/data-binding/guide.html
其中的Resources章节中的后面2个还未理解。希望大家多多留言交流~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/320747?site
推荐阅读
相关标签
  

闽ICP备14008679号