在Android中如何使用DataBinding详解(Kotlin)

 更新时间:2020年11月09日 11:59:22   作者:simon大佬  
这篇文章主要给大家介绍了关于在Android中如何使用DataBinding(Kotlin)的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

本问主要介绍DataBinding在Android App中的使用方法。数据绑定是将“提供器”的数据源与“消费者”绑定并使其同步的一种通用技术。

1. Android应用程序使用数据绑定

1.1 介绍DataBinding

Android通过DataBinding提供了编写声明型布局的支持。这样可以最大程度简化布局和逻辑相关联的代码。
数据绑定要求修改文件,外层需要包裹一个layout布局。主要通过@{} 或 @={}语法把布局中的元素和表达式的引用写入到属性中。

<?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="mainModel"
   type="me.ithome.jetpack.model.MainViewModel" />①
 </data>

 <androidx.constraintlayout.widget.ConstraintLayout
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity">②

  <TextView
   android:id="@+id/tv_userinfo"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@{mainModel.userData.toString()}"
   app:layout_constraintBottom_toBottomOf="parent"
   app:layout_constraintLeft_toLeftOf="parent"
   app:layout_constraintRight_toRightOf="parent"
   app:layout_constraintTop_toTopOf="parent" />

  <Button
   android:id="@+id/button"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_marginTop="56dp"
   android:onClick="@{(view) -> mainModel.getClick(view)}"
   android:text="@string/btn_getUserInfo"
   app:layout_constraintBottom_toTopOf="@+id/tv_userinfo"
   app:layout_constraintEnd_toEndOf="parent"
   app:layout_constraintHorizontal_bias="0.498"
   app:layout_constraintStart_toStartOf="parent"
   app:layout_constraintTop_toTopOf="parent" />

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

①用户变量,定义了能在这个布局里面使用的属性和类

②常规布局

DataBinding会基于layout创建一个Binding class,这个类包含了布局属性(定义的变量)到相关视图的所有绑定,并且会为布局中的数据元素生成setter,生成的类的名称是基于layout的名称(驼峰命名,加上Binding后缀)。比如布局名是activity_main.xml,生成的类就是ActivityMainBinding。你能通过这个类去inflate布局和数据模型,也可以通过DataBindingUtil类。

DataBindingUtils加载布局

val mainBindingUtil = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
mainBindingUtil.lifecycleOwner = this

inflate加载布局(此方法也能用于RecyclerView, ViewPager)

val mainBindingUtil = ActivityMainBinding.inflate(layoutInflater)
setContentView(mainBindingUtil.root)

上述两种方法大家二选一,一般在Activity中我们都用第一种。

1.2 如何启用DataBinding

想要在Android App工程中使用databinding,只需要在app/build.gradle文件中设置如下代码:

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

1.3 DataBinding点击事件的处理

布局的处理除了数据的传递,还有点击事件的处理。

使用方式和普通方法调用一样。比如我在MainViewModel.kt中定义了getClick方法

fun getClick(v: View) {
 //TODO
}

现在我想在Button点击的时候调用getClick方法,只需要在布局文件中添加下面的代码

android:onClick="@{(view) -> mainModel.getClick(view)}"

如果不需要参数,可以直接

android:onClick="@{() -> mainModel.getClick()}"

如果有其他参数,对应的添加参数列表

android:onClick="@{() -> mainModel.getClick(args)}"

其他比如onLongClick之类的处理都是同理。

1.4 import的使用

可以通过import的方式导入类,直接调用类的静态方法。

<data>
 <import type="me.ithome.jetpack.utils.StringUtils" />
 <variable
  name="mainModel"
  type="me.ithome.jetpack.model.MainViewModel" />
</data>

<TextView
 android:text="@{StringUtils.capitalize(mainModel.userData.name)}"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"/>

1.5 数据实时刷新

当viewmodel的数据发生变化后,我们希望布局也同时刷新,有个非常简单的方法,不需要继承BaseObservable,我们通过引入LiveData来实现。

open class MainViewModel : ViewModel() {

  var userData: MutableLiveData<UserInfo> = MutableLiveData()

  init {
    getUserInfo()
  }

  private fun getUserInfo() {
    val user = UserInfo("李四", (10..50).random())
    userData.postValue(user)  //数据发生变化后,调用postValue,无需通过observe监听,布局数据会自动刷新
  }

  fun getClick(v: View) {
    getUserInfo()
  }
}

1.6 使用BindingAdapter

可以通过BindingAdapter这个注解来实现属性值变化的时候,控件状态也跟着变化,比如图片ImageView,当url变化的时候,控件会跟着显示不同的图片。

需要在静态类里面定义一个静态方法:

object StringUtils {

  @BindingAdapter("android:src")
  @JvmStatic fun loadImage(view: ImageView, url: String) {
    MyApplication._context?.let {
      Glide.with(it)
        .load(url)
        .into(view)
    }
  }
}

注意这里的android:src,这个可以直接指定控件的属性,也可以自己定义属性。

<ImageView
      android:id="@+id/imageView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/tv_userinfo"
      android:src="@{mainModel.imageUrl}"
      tools:srcCompat="@tools:sample/avatars" />

loadImage方法绑定的是android:src这个属性,所以当这个属性的值变化时会把view和url传递到loadImage。

如果是绑定的自定义字段呢?比如我现在绑定了一个自定义的url。

@BindingAdapter("url")
@JvmStatic fun loadImage(view: ImageView, url: String) {
...
}

那么布局文件就这么写

<ImageView
      android:id="@+id/imageView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/tv_userinfo"
      app:url="@{mainModel.imageUrl}"
      tools:srcCompat="@tools:sample/avatars" />

总结

前面主要是写了databinding的一些基本用法,扩展用法还比较多,我们后续再接着说。

到此这篇关于在Android中如何使用DataBinding(Kotlin)的文章就介绍到这了,更多相关Android使用DataBinding(Kotlin)内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Android天气预报app改进版

    Android天气预报app改进版

    这篇文章主要为大家详细介绍了改进版的Android天气预报app,内容更加充实,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-07-07
  • Android多线程之同步锁的使用

    Android多线程之同步锁的使用

    本篇文章主要介绍了Android多线程之同步锁的使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-08-08
  • Android 自定义EditText输入框带清空按钮

    Android 自定义EditText输入框带清空按钮

    这篇文章主要介绍了Android 自定义EditText输入框带清空按钮的相关资料,需要的朋友可以参考下
    2017-05-05
  • Android开发笔记XML数据解析方法及优缺点

    Android开发笔记XML数据解析方法及优缺点

    XML数据是一种常见的数据格式,Android开发中需要对其进行解析。常用的XML解析方式有DOM、SAX、Pull和Json等,每种方式都有其优缺点。开发者可以根据具体需求选择合适的解析方式,提高数据解析效率和性能
    2023-05-05
  • Android自定义View实现水波纹引导动画

    Android自定义View实现水波纹引导动画

    这篇文章主要为大家详细介绍了Android自定义View实现水波纹动画引导,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-01-01
  • Flutter进阶之实现动画效果(九)

    Flutter进阶之实现动画效果(九)

    这篇文章主要为大家详细介绍了Flutter进阶之实现动画效果的第九篇,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-08-08
  • Android 中 ActivityLifecycleCallbacks的实例详解

    Android 中 ActivityLifecycleCallbacks的实例详解

    这篇文章主要介绍了Android 中 ActivityLifecycleCallbacks的实例详解的相关资料,希望通过本文大家能掌握这部分内容,需要的朋友可以参考下
    2017-09-09
  • Android检测手机多点触摸点数的方法

    Android检测手机多点触摸点数的方法

    这篇文章主要为大家详细介绍了Android检测手机多点触摸点数的方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-05-05
  • Android Selector获取焦点后文本背景修改的实现代码

    Android Selector获取焦点后文本背景修改的实现代码

    这篇文章主要介绍了Android Selector获取焦点后文本背景修改的实现代码,本文通过demo展示和实现代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-11-11
  • Android中TextView局部变色功能实现

    Android中TextView局部变色功能实现

    这篇文章给大家详细讲解了一下Android中TextView实现部分文字不同颜色的功能实现过程,有这方面需要的朋友们一起学习下吧。
    2017-12-12

最新评论