本文主要介绍
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