Jetpack:Databinding组件

DataBinding介绍

DataBinding是一个支持库,顾名思义:数据绑定,它可以将布局页面中的组件与应用中的数据绑定,它支持单向绑定与双向绑定,所谓单向绑定是指数据的变化会驱动页面的变化。而双向绑定除此之外还支持页面的变化驱动数据的变化,

DataBinding只是一种工具,它解决的是View和数据之间的绑定。MVVM是一种架构模式,两者是有本质区别的。

使用DataBinding

如果想在应用中使用DataBinding,需要在应用的build.gradle文件中添加dataBinding配置,如下所示:

android {
    ...
    dataBinding {
        enabled = true
    }
}

对应的DataBinding布局

最外层变为layout元素,里面包裹了data元素和常规的布局元素。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"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="data"
            type="com.fate.jetpackdatabinding.MyViewModel" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{String.valueOf(data.number)}" />

        <Button
            android:id="@+id/btn"
            android:onClick="@{()->data.add()}"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>

</layout>


编写布局完后,重新编译,系统会为每个使用了DataBinding的布局文件生成一个对应的绑定类。默认情况下,类名是基于布局文件的名称,它会转换为驼峰形式并在末尾添加Binding后缀。

以布局文件activity_main.xml为例,那么生成的类名是ActivityMainBinding,然后需要使用DataBindingUtil将数据进行绑定.

如果绑定的是 LiveData,那么在子线程更新数据,可以使用 postValue。

public class MainActivity extends AppCompatActivity {

    MyViewModel myViewModel;
    ActivityMainBinding activityMainBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);
        myViewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(MyViewModel.class);
        activityMainBinding.setData(myViewModel);
        activityMainBinding.setLifecycleOwner(this);
    }
}

activityMainBinding.setData(myViewModel);中的setData 对应的就是布局文件中定义的变量的名字,两者需要对应。

public class MyViewModel extends ViewModel {

    private MutableLiveData<Integer> number;

    public MutableLiveData<Integer> getNumber(){
        if(number == null){
            number = new MutableLiveData<>();
            number.setValue(0);
        }
        return number;
    }

    public void add(){
        number.setValue(number.getValue() + 1);
    }

}

表达式语法

DataBinding支持在布局文件中使用以下运算符、表达式和关键字:

  • 算术运算符 + - / * %
  • 字符串连接运算符 +
  • 逻辑运算符 && ||
  • 二元运算符 & | ^
  • 一元运算符 + - ! ~
  • 移位运算符 >> >>> <<
  • 比较运算符 == > < >= <=(请注意,< 需要转义为 <)
  • instanceof
  • 分组运算符 ()
  • 字面量运算符 - 字符、字符串、数字、null
  • 类型转换
  • 方法调用
  • 字段访问
  • 数组访问 []
  • 三元运算符 ?:

变量

data元素中使用variable来定义变量,支持多个variable

<!--定义变量-->
<data>
    <variable name="user" type="com.gfd.demo.User"/>
    <variable name="image" type="Drawable"/>
    <variable name="str" type="String"/>
</data>

<!--使用变量-->
android:text="@{user.name}"

资源引用

<string name="nameFormat">%s---%s</string>  
<!--字符串拼接-->
android:text="@{@string/nameFormat(vm.firstName, vm.lastName)}"

android:padding="@{vm.large? @dimen/largePadding : @dimen/smallPadding}"

Null 合并运算符

android:text="@{vm.displayName ?? vm.lastName}"

导入

通过import,可以在布局中使用导入类型的属性

<data>
    <!-- 引入View -->
    <import type="android.view.View" />
    <variable
        name="vm"
        type="com.gfd.demo.Demo" />
</data>

android:visibility="@{vm.state == 1 ? View.INVISIBLE : View.VISIBLE}"

布局中使用到了View.VISIBLE,所以必须导入View,否则编译报错。支持多个import语句,默认会自动导入java.lang.*,除此之外必须手动导入。

当导入多个类型时,类型可能会冲突。当类名有冲突时,可以使用别名重命名:

<import type="android.view.View"/>
<import type="com.gfd.demo.View"
        alias="Vista"/>

集合

<data>
    <import type="android.util.SparseArray"/>
    <import type="java.util.Map"/>
    <import type="java.util.List"/>
    <variable name="list" type="List&lt;String>"/>
    <variable name="sparse" type="SparseArray&lt;String>"/>
    <variable name="map" type="Map&lt;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]}"

&lt;是特殊符号“<”,List&lt;String>等价于List<String>,因为定义在xml中,所以必须使用转义。

包含

当在布局中使用include引入布局时,需要使用命名空间和特定的变量名称来给引入布局中的变量赋值。

<?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.gfd.demo.User"/>
   </data>
   <LinearLayout
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <!-- 使用bind给引入的布局中定义的变量赋值 -->
       <include 
          android:id="@+id/include"
          layout="@layout/layout_name"
          bind:isShow="@{user.isShow}"/>
   </LinearLayout>
</layout>

layout_name.xml:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    <!-- 定义一个变量isShow ,在引入的地方,要使用该变量名赋值-->
    <data>
        <variable
            name="isShow"
            type="boolean" />
    </data>
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="@{isShow ? View.VISIBLE : View.GONE}"
            app:layout_constraintStart_toStartOf="parent"/>

   </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

事件绑定

DataBinding中的事件绑定支持两种方式:方法引用和监听器。下面分别看一下这两种的使用方式:
方法引用

<data>
    <variable
        name="click"
        type="com.gfd.demo.DemoActivity" />
</data>

<Button
    android:id="@+id/btnLogin"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="@{click::login}" /><!-- 调用click中的login方法 -->

class DemoActivity:AppCompatActivity(){
  ...
  fun login(view:View){
    ...
  }
  ...
}

该方式事件可以直接绑定到处理的方法,类似View在Activity中的方法android:onClick。触发的方法必须符合监听器方法的签名(以onClick事件为例,方法含有一个View类型的参数)。它是在编译时处理的,如果该方法不存在或其签名不正确,则编译不通过。

监听器绑定

<data>
    <variable
        name="info"
        type="com.gfd.demo.Info" />
    <variable
        name="click"
        type="com.gfd.demo.DemoActivity" />
</data>

<Button
    android:id="@+id/btnLogin"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="@{()-> click.login(info)}" /><!-- 调用click中的login方法 -->

class DemoActivity:AppCompatActivity(){
  ...
  fun login(info:Info){
    ...
  }
  ...
}

使用监听器的方式,我们可以自定义方法的参数类型,比较灵活。

注意:设置事件绑定后,别忘记赋值binding.click = this(这里的this指的是activity对象,可以设置成任何对象,要与data元素type定义的类型一致)

自定义属性@BindingAdapter

如果我们想在自定义属性上使用DataBinding,需要使用注解:@BindingAdapter来实现自己的逻辑。比如:给ImageView增加一个属性imgUrl用来显示网络图片。

  • 它作用于方法,和类无关,这个自定义属性的方法可以写在任何地方。
  • 对应的方法必须为公共静态方法(public static),可以有一到多个参数。
@BindingAdapter(value = ["app:imgUrl"])
fun loadImage(imageView: ImageView, url: String?) {
    Glide.with(imageView.context)
        .load(url)
        .into(imageView)
}

//多个参数
@BindingAdapter(value = ["app:imgUrl","app:placeholder"], requireAll = false)
fun loadImg(imageView: ImageView, url: String?, placeholder: Drawable?) {
    Glide.with(imageView.context)
        .load(url)
        .placeholder(placeholder)
        .into(imageView)
}

//使用
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:imgUrl="@{vm.url}"/>

requireAll = false表示我们可以使用这两个两个属性中的任一个或同时使用,

如果requireAll = true则两个属性必须同时使用,不然报错。默认为true。 对于Kotlin来定义静态方法,把它直接定义在一个.kt文件中即可。或者使用object常见报错

更改调用方法@BindingMethods

@BindingMethods(value = [
    BindingMethod(
        type = android.widget.ImageView::class,
        attribute = "android:tint",
        method = "setImageTintList")])

这样使属性android:tintsetImageTintList(ColorStateList)方法关联。

使用DataBinding可以在Activity中减少对View的操作,有效的减少代码量,大大提供了开发效率,但是在xml中有些语法还不支持提示,容易写错,而且一旦写错,编译就会报错,如果编译器不提示详细的错误信息,可以使用命令gradlew compileDebugSource --stacktrace -info或者点击Android Studio右侧Gradle-app->other->assembleDebug来查看具体的错误。

支持双向绑定

比如 EditText,绑定了 LiveData,当 EditText 内容改变的时候,LiveData 的内容也会跟着变化。如下:

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@={viewModel.editText}"
    />

关键就是 @={},如此一来,我们就可以直接在 ViewModel 中取得 EditText 的内容数据了,因为 ViewModel 是不可以持有 View 实例的,所以如果没有 DataBinding,要获取 EditText 就只能通过 View 传给 ViewModel。有了 DataBinding 就方便多啦。

当您使用下表中的特性时,该平台提供对双向数据绑定的内置支持。有关平台如何提供此类支持的详细信息,请参阅相应绑定适配器的实现:

特性 绑定适配器
AdapterView android:selectedItemPosition
android:selection
AdapterViewBindingAdapter
CalendarView android:date CalendarViewBindingAdapter
CompoundButton android:checked CompoundButtonBindingAdapter
DatePicker android:year
android:month
android:day
DatePickerBindingAdapter
NumberPicker android:value NumberPickerBindingAdapter
RadioButton android:checkedButton RadioGroupBindingAdapter
RatingBar android:rating RatingBarBindingAdapter
SeekBar android:progress SeekBarBindingAdapter
TabHost android:currentTab TabHostBindingAdapter
TextView android:text TextViewBindingAdapter
TimePicker android:hour
android:minute
TimePickerBindingAdapter

Google Developers

猜你喜欢

转载自blog.csdn.net/PrisonJoker/article/details/114609372