Jetpack-DataBinding

307 阅读6分钟

DataBinding

DataBinding是一个支持库,顾名思义:数据绑定,它可以将布局页面中的组件与应用中的数据绑定,它支持单向绑定与双向绑定,所谓单向绑定是指数据的变化会驱动页面的变化。而双向绑定除此之外还支持页面的变化驱动数据的变化,比如页面中有一个 EditText,数据的变化可以改变它的显示内容,我们输入的内容也可以改变绑定的数据。

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

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

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

在布局文件中,选中根布局的View,按住 Alt + 回车键,点击“Convert to data binding layout”,转换成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">

    <data>
        <variable
            name="vm"
            type="com.gfd.demo.MyViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{vm.name}"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

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

android:text="@{vm.name}"等价于tvName.text = mViewModel.name这样就将数据和View相关联了。

编写布局完成后,需要重新编译,编译成功后系统会为每个使用了DataBinding的布局文件生成一个对应的绑定类。默认情况下,类名是基于布局文件的名称,它会转换为驼峰形式并在末尾添加Binding后缀。以布局文件名为activity_text.xml为例,那么生成的类名为ActivityTestBinding,然后需要使DataBindingUtil将数据进行绑定。

class MainActivity : AppCompatActivity() {

    private lateinit var mViewModel: MyViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
        val binding :ActivityTestBinding = DataBindingUtil.setContentView(this,R.layout.activity_test)
        binding.vm = mViewModel
    }
}

binding.vm中的vm就是布局文件中定义的变量的名字,两者要对应。

表达式语法

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

定义了三个变量:user、image和str,在布局中直接使用变量来绑定对应的View。

资源引用

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

如果左侧不为null,则为左侧的值,否则为右侧的值。

导入

通过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来查看具体的错误。

KotlinAndroid

关注公众号,获取更多资源