DataBinding 基础用法

DataBinding使用注意事项点:
1、变量声明variable后,需要在binding中赋值
2、xml中用到的类,需要import,如控制View的显示隐藏,需要导入View类
3、int类型对应为Integer,且在@{}用于text时候,需要转为String
4、在@{}中可以使用``反引号作为String,注意非英文编码可能出错,甚至会编译报错
5、资源引用使用@string、@color、@drawable等,IDE不会补全,注意拼写无误
6、使用default设置默认值,用于预览编辑
7、null判空配合??使用,默认值可以``反引号、资源引用或者变量、静态函数值
8、String的format使用也是可以``、@string或者其他变量等
9、静态函数,java的写法和kotlin的写法不同,实质都是jvm虚拟机的静态函数化
10、函数调用的多种写法,无参、有参、context,以及静态函数调用(针对对象,而非类)。

1. 配置文件,启动 dataBinding,在 Application Module的build.gradle中

apply plugin: 'org.jetbrains.kotlin.kapt' //必须

android {
    //方式1 AS 4.0以下
    /*dataBinding {
        enabled = true
    }*/

    //方式二 AS 4.1之后
    buildFeatures{
        dataBinding = true
        //for view binding
        //viewBinding = true
    }
}

2. 项目 build.gradle 中

plugins {
    id "org.jetbrains.kotlin.kapt" version '1.7.10' apply false
}

3. 布局文件 activity_base_use.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools">
    <!--用于 xml 布局中 binding 数据的一些变量,类的声明引用-->
    <data>
        <!--变量声明,使用variable 需要在代码中初始化和赋值,基础数据类型的使用-->
        <variable
            name="title"
            type="String" />

        <variable
            name="age"
            type="Integer" />

        <variable
            name="name"
            type="String" />

        <variable
            name="isStudent"
            type="Boolean" />
        <!--List和Map类型,在xml中,个别字符需要转义符号-->
        <variable
            name="ages"
            type="List&lt;String>" />

        <variable
            name="map"
            type="Map&lt;Integer,String>" />
        <!--用于演示静态引用点击-->
        <variable
            name="helper"
            type="BindHelp" />
        <!--导入xml中需要的类,不导入的话,引用不到,使用就会报错-->
        <import type="android.view.View" />

        <import type="java.util.List" />

        <import type="java.util.Map" />

        <import type="org.hanyang.jetpack.binding.tools.BindTool" />

        <import type="org.hanyang.jetpack.binding.tools.BindUtilKt" />
        <!-- 可使用 alias 命名别名,就可以在xml内部应用时候使用别名,优化书写和区分 -->
        <import
            alias="BU"
            type="org.hanyang.jetpack.binding.tools.BindUtil" />

        <import type="org.hanyang.jetpack.binding.tools.BindHelp" />
    </data>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="10dp">
        <!--使用databinding,则会将每个配置id的控件在对应的Java的binding类中,生成控件引用。
            使用@{}符号引用导入/定义的属性,但是这些引入对象,需要在本xml对应的activity/fragment中的binding设置set赋值。如下title等变量,就要在activity中设置title的值。-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal">
            <!--1.普通的应用变量: title, 使用tools命名空间的属性,便于预览效果
            todo 注意text不能为Int值,否则报错。int 要转为string,使用拼接,或者valueOf,toString都可以。-->
            <androidx.appcompat.widget.AppCompatTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:text="@{age+ ` years old`}"
                tools:text="title text" />
            <!--2、使用资源引用(不只是string,可以color,drawable等其他需要的。)
              :在@{}里面写@string的时候,不会自动提示和补全,所以切记别写错了,否则编译错误,排查问题都不容易-->
            <androidx.appcompat.widget.AppCompatTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:text="@{@string/str_reference}"
                tools:text="str 引用" />
            <!--3、默认值的使用:default用,分号分隔,只是用于预览作用,运行时无效。
              可以使用``反引号;也可以@string引用资源;也可使用其他变量或者静态函数值-->
            <androidx.appcompat.widget.AppCompatTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:text="@{name, default = `默认Name`}" />
            <!--4、判空null,并设置默认值,使用?? 若空则显示默认值。
			 todo 注意,``反引号内尽量避免中文,因为编码会显示乱码,或者运行时可能报错。
			 todo 用``地方都可 用@string或这其他变量值,静态函数值 替换。
			 ??后可用``,@string/str_reference,或者其他变量或静态函数值。如:
			android:text="@{title ?? @string/str_reference}"
			 -->
            <androidx.appcompat.widget.AppCompatTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:text="@{title ?? `null of title`}" />
            <!--5、使用string的format-->
            <androidx.appcompat.widget.AppCompatTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:text="@{@string/str_format(`zhangsan`)}" />
            <!--6、字符拼接-->
            <androidx.appcompat.widget.AppCompatTextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:text="@{`Pre_` + @string/str_reference + title}"
                tools:text="str 的拼接" />
        </LinearLayout>
        <!--7、根据boolean类型,控制显示隐藏(也可用于其他判断)
          todo 注意这里也能用default,用于预览,但是值就要写成未使用binding时候的默认string值的写法。如这里的gone
         -->
        <androidx.appcompat.widget.AppCompatTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="是学生就显示"
            android:textColor="@android:color/holo_green_light"
            android:visibility="@{isStudent ? View.VISIBLE : View.GONE, default = `gone`}" />
        <!--复数,与自然语言相关,特别是不同国家的语言对应不同的单复数。目前没有业务场景使用到,未做研究-->
        <androidx.appcompat.widget.AppCompatTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text="@{@plurals/str_numbers(0)}"
            tools:text="str的格式化" />
        <!--8、使用静态函数值,分别是java方式,kotlin 的两种方式-->
        <androidx.appcompat.widget.AppCompatTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{BindTool.nameAge(name, age)}"
            android:textColor="@android:color/holo_blue_light"
            tools:text="静态函数" />

        <androidx.appcompat.widget.AppCompatTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{BindUtilKt.ageName(age,name)}"
            android:textColor="@{isStudent?@android:color/holo_blue_light:@android:color/holo_purple}"
            tools:text="kt 静态函数" />
        <!--这里的BU是上面定义的BindUtil的别名-->
        <androidx.appcompat.widget.AppCompatTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{BU.ageAge(age) + BindHelp.nameName(name)}"
            android:textColor="@android:color/holo_purple"
            tools:text="Kt object 静态函数" />
        <!--9、List和Map -->
        <androidx.appcompat.widget.AppCompatTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{ages[1] +` `+ map[20]}"
            android:textColor="@android:color/holo_purple"
            tools:text="list和map" />
        <!--10、函数调用。点击按钮事件的响应,在onClick函数中,有多种写法
          todo 其实也是 binding 在 xml 中函数调用的一种写法。只不过这里的函数是 click 而已-->
        <androidx.appcompat.widget.AppCompatButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="@{()->BindTool.log()}"
            android:text="普通无参(Logcat)" />

        <androidx.appcompat.widget.AppCompatButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="@{(v)->BindTool.toast(v)}"
            android:text="普通View参数"
            android:textAllCaps="false" />

        <androidx.appcompat.widget.AppCompatButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="@{()->BindUtilKt.toastV(context)}"
            android:text="Context参数"
            android:textAllCaps="false" />

        <androidx.appcompat.widget.AppCompatButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="@{BindHelp::staticClick}"
            android:text="静态函数应用点击" />
    </LinearLayout>
</layout>

4. 工具类
  4.1 BindTool.java

/**
 * java版的用于xml的dataBinding的静态函数类,kotlin的写法,参照BindUtil中
 */
public class BindTool {

    /**
     * 简单的一个静态函数,databinding在xml中使用的函数,必须是public的static函数
     *
     * @param name 名称
     * @param age  年龄
     * @return string的拼接
     */
    public static String nameAge(String name, int age) {
        return name + age;
    }

    /**
     * 点击就打印一个log
     */
    public static void log() {
        Log.i("BindTool", "dataBinding的普通点击,静态java函数的log日志");
    }

    /**
     * 使用view参数,显示toast
     *
     * @param view view控件
     */
    public static void toast(View view) {
        Toast.makeText(view.getContext(), "普通点击View显示Toast", Toast.LENGTH_SHORT).show();
    }
}

  4.2 BindUtil.kt

/**
 * ----------------------------------------------------------------
 * todo Kotlin的一大特点,文件内可以多个类,函数。java则不能多个public的类,也不能函数。
 * 用于xml中dataBinding的静态函数.不同于java的public static函数写法。这里kotlin中有两种写法:
 * 1、直接定义在kt文件的top level顶级,直接写函数名。调用方导入BindUtilKt,使用BindUtilKt.ageName应用。
 * 2、定义在一个静态类object中。在kotlin中就是object的静态类,或者companion object的类中。需要@jvmStatic标记才有效
 */

/**
 * 用于xml的 databinding 中,这是在 kt 文件顶级写法,不需要 static 标记
 */
fun ageName(age: Int, name: String?): String {
    return "Kt 函数: $age $name"
}

/**
 * [context] 参数弹toast
 */
fun toastV(context: Context) {
    Toast.makeText(context, "Context弹出Toast", Toast.LENGTH_SHORT).show()
}

/**
 * 这是在 class 类中 companion 的object 中
 */
class BindUtil {
    companion object {
        @JvmStatic
        fun ageAge(age: Int): String {
            return "年龄 $age"
        }
    }
}

/**
 * 写在object中
 */
object BindHelp {
    @JvmStatic
    fun nameName(name: String?): String {
        return "姓名 $name"
    }

    /**
     * 用于view的静态点击
     */
    @JvmStatic
    fun staticClick(view: View) {
        Toast.makeText(view.context, "静态函数引用", Toast.LENGTH_SHORT).show()
    }
}

5. 测试页面 BindingActivity.kt

/**
 * dataBinding的基础用法演示界面
 */
class BaseUseActivity : AppCompatActivity() {
    /*
      DataBinding使用步骤简要:
      1、使用最新版的AndroidStudio,至少AS3.0以上吧。
      2、在项目module下的build.gradle的android闭包下,配置 databinding{enabled=true}
      3、对于布局的xml文件,将原有的正常布局,外面用<layout></layout>包裹作为跟节点。<data></data>节点下存放用于xml布局的一些变量,工具类之类的
      4、在代码无误的情况下,build一下module或整个project。然后就可以在代码中使用binding方式coding了。
     */

    //<editor-folder desc="成员变量代码块">
    //</editor-folder>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //Activity使用DataBindingUtil.setContentView的方式关联xml布局文件,替代原有的setContentView方式。其中`ActivityBaseUseBinding`为databinding根据xml自动生成的类文件
        //命名方式为layout的name+Binding。(可以自定义名称,在<data>标签内的className属性)
        val binding = DataBindingUtil.setContentView<ActivityBaseUseBinding>(
            this,
            R.layout.activity_base_use
        )
        //设置在xml中声明的变量值
        binding.age = 20
        binding.isStudent = true
        binding.title = "BD标题"
        //BindName
        binding.name = "Na"
        //list,map 这里的ages和map,赋值给xml中的变量
        val ages = listOf("20", "30", "10")
        val map = mapOf(19 to "Lily", 21 to "Jim", 20 to "Aili")
        binding.ages = ages
        binding.map = map
        //静态点击的helper
        binding.helper = BindHelp
    }
}

6. 效果图

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Dinding是一种通过机制,将代码中的数据和XML(UI)进行绑定的技术。它允许双方都能对数据进行操作,并在数据发生变化时自动刷新数据。 在Android中,我们可以使用DataBindingUtil类的方法来创建Databinding实例,即通过DataBindingUtil.inflate(LayoutInflater, layoutId, parent, attachToParent)或DataBindingUtil.bindTo(viewRoot, layoutId)方法来得到绑定对象。 Databinding主要解决了Model层与View交互的问题,并且现在也支持双向绑定。它的优势在于可以简化代码,使得数据与UI更紧密地结合。我们可以通过一个登录的例子来进一步感受Databinding的优势。你可以下载并查看一个登录的Demo,或者自己编写相关的例子来深入理解Databinding用法和好处。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [DataBinding详解](https://blog.csdn.net/peiyuWang_2015/article/details/76945081)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [DataBinding使用教程详解](https://blog.csdn.net/zhangwude2301/article/details/80069972)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hanyang Li

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值