android studio 使用 databinding 基础配置
使用步骤:
1.app 的 build.gradle 加入 下图代码
2.xml外部新增 <layout>标签
activity 布局文件
<?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> <!--这种方式声明变量 可以解决同一个包名,有两对象的绑定,根据alias区别对象--> <import alias="myUser" type="com.kxt.mydatabinding.data.User" /> <import alias="myListener" type="com.kxt.mydatabinding.listener.MyListener" /> <import type="com.kxt.mydatabinding.MainActivity.Listener" alias="myClick"/> <variable name="user" type="myUser" /> <variable name="listener" type="myListener" /> <variable name="click" type="myClick"/> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:id="@+id/txt" android:layout_width="match_parent" android:layout_height="wrap_content" /> <!--调用方法--> <TextView android:id="@+id/name" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="@{()->listener.logName(user)}" android:text="@{user.name}" /> <!--调用监听器--> <TextView android:id="@+id/gender" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="@{listener::logGender}" android:text="@{user.gender??user.name}" /> <TextView android:id="@+id/address" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@={user.address}" /> <!--表达式--> <TextView android:id="@+id/phone" android:layout_width="match_parent" android:layout_height="wrap_content" android:text='@{1>2?user.phone:"15888888888"}' /> <!--输入框文本编辑后,user.address的值会同步到代码中--> <EditText android:id="@+id/address_edt" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@={user.address}" /> <Button android:id="@+id/btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="刷新" android:onClick="@{()->click.refresh()}"/> </LinearLayout> </layout>
3.MainActivity.java
4.User.java
5.MyListener.java