这里介绍数据绑定库双向绑定的两种写法。第一种是模型类继承Observable,两个属性username、password的get方法上面添加@bindable注解。第二种是创建一个包裹类,使用
ObservableField字段,然后再调用 this.observableField.get()获取字段。
1.实现方案1
模型类继承Observable
1.1实现步骤
step1.增加绑定配置
修改app模块下的build.gradle文件,增加如下内容:
dataBinding{enabled = true;}
step2.修改布局文件
点根节点LinearLayout,按Alt+Enter弹出快捷菜单,点击其中Convert to data binding layout。使用双向绑定的格式是:
@={}:双向绑定,修改控件的值后,同步修改模型属性值
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"><data><variablename="user"type="com.gaoting.twowaybinding.User" /></data><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity"><EditTextandroid:layout_margin="20dp"android:text="@={user.userName}"android:id="@+id/edtUserName"android:layout_width="wrap_content"android:layout_height="wrap_content"android:hint="请输入用户名!" /><EditTextandroid:layout_margin="20dp"android:text="@={user.password}"android:id="@+id/edtPassword"android:layout_width="wrap_content"android:layout_height="wrap_content"android:hint="请输入密码!" /></LinearLayout>
</layout>
step3.在Activity中使用
1)创建模型对象,必须继承BaseObservable
@Bindable:声明改属性可以用于绑定
修改set方法,调用notifyPropertyChanged(BR.userame)发送修改通知。
package com.gaoting.twowaybinding;import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;public class User extends BaseObservable {public User(String userName, String password) {this.userName = userName;this.password = password;}String userName;String password;@Bindablepublic String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;notifyPropertyChanged(BR.userName);}@Bindablepublic String getPassword() {return password;}public void setPassword(String password) {this.password = password;notifyPropertyChanged(BR.password);}
}
2)修改Activity,使用binding对象
ActivityMainBinding是框架自动生成的,和MainActivity对应
使用DataBindingUtil.setContentView(this, R.layout.activity_main)获取绑定对象
去掉setContentView(R.layout.activity_main)
activityMainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);user = new User("gaoting","123456");activityMainBinding.setUser(user);
3)增加观察者,打印日志
user.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {@Overridepublic void onPropertyChanged(Observable sender, int propertyId) {if(propertyId == BR.userName){Log.i(TAG,"我收到了userName值的变化通知,userName="+user.userName);}else if(propertyId == BR.password){Log.i(TAG,"我收到了password值的变化通知,password="+user.password);}}});
step4.调试验证方法
1)修改布局文件(activty_main.xml )
增加打印User和修改User按钮实现修改数据源值看UI控件有无变化,以及修改控件值看数据源有无变化。
<Buttonandroid:layout_margin="20dp"android:id="@+id/btPrintUser"android:text="打印User"android:layout_width="wrap_content"android:layout_height="wrap_content"/><Buttonandroid:layout_margin="20dp"android:id="@+id/btChangeUser"android:text="修改User"android:layout_width="wrap_content"android:layout_height="wrap_content"/>
修改MainActivity.java,增加监听代码。
activityMainBinding.btPrintUser.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Log.i(TAG,"userName="+user.userName+",password="+user.password);}});activityMainBinding.btChangeUser.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {user.userName = "gaotingchange";user.password = "123456change";activityMainBinding.setUser(user);}});
调试,可以在LogCat中查看打印日志。
1.2完整代码
1)activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"><data><variablename="user"type="com.gaoting.twowaybinding.User" /></data><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity"><EditTextandroid:layout_margin="20dp"android:text="@={user.userName}"android:id="@+id/edtUserName"android:layout_width="wrap_content"android:layout_height="wrap_content"android:hint="请输入用户名!" /><EditTextandroid:layout_margin="20dp"android:text="@={user.password}"android:id="@+id/edtPassword"android:layout_width="wrap_content"android:layout_height="wrap_content"android:hint="请输入密码!" /><Buttonandroid:layout_margin="20dp"android:id="@+id/btPrintUser"android:text="打印User"android:layout_width="wrap_content"android:layout_height="wrap_content"/><Buttonandroid:layout_margin="20dp"android:id="@+id/btChangeUser"android:text="修改User"android:layout_width="wrap_content"android:layout_height="wrap_content"/></LinearLayout>
</layout>
2)MainActivity.java
package com.gaoting.twowaybinding;import android.os.Bundle;
import android.util.Log;
import android.view.View;import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.Observable;import com.gaoting.twowaybinding.databinding.ActivityMainBinding;public class MainActivity extends AppCompatActivity {final String TAG = "MainActivity";ActivityMainBinding activityMainBinding;User user;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);activityMainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);user = new User("gaoting","123456");activityMainBinding.setUser(user);user.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {@Overridepublic void onPropertyChanged(Observable sender, int propertyId) {if(propertyId == BR.userName){Log.i(TAG,"我收到了userName值的变化通知,userName="+user.userName);}else if(propertyId == BR.password){Log.i(TAG,"我收到了password值的变化通知,password="+user.password);}}});activityMainBinding.btPrintUser.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Log.i(TAG,"userName="+user.userName+",password="+user.password);}});activityMainBinding.btChangeUser.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {user.userName = "gaotingchange";user.password = "123456change";activityMainBinding.setUser(user);}});}}
3)User.java
package com.gaoting.twowaybinding;import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;public class User extends BaseObservable {public User(String userName, String password) {this.userName = userName;this.password = password;}String userName;String password;@Bindablepublic String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;notifyPropertyChanged(BR.userName);}@Bindablepublic String getPassword() {return password;}public void setPassword(String password) {this.password = password;notifyPropertyChanged(BR.password);}
}
2.实现方案2
使用ObservableField包裹模型对象。
2.1实现步骤
实现步骤如下:
1)模型对象类
package com.gaoting.twowaybinding;import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;public class User{public User(String userName, String password) {this.userName = userName;this.password = password;}String userName;String password;public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}
}
2)包裹类
package com.gaoting.twowaybinding;import androidx.databinding.ObservableField;public class TwoWayBinding {ObservableField<User> observableField = new ObservableField<>();public TwoWayBinding(User user){observableField.set(user);}public String getUserName() {return observableField.get().userName;}public void setUserName(String userName) {this.observableField.get().userName = userName;}public String getPassword() {return observableField.get().password;}public void setPassword(String password) {this.observableField.get().password = password;}
}
3)使用包裹类
package com.gaoting.twowaybinding;import android.os.Bundle;
import android.util.Log;
import android.view.View;import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.Observable;import com.gaoting.twowaybinding.databinding.ActivityMainBinding;public class MainActivity extends AppCompatActivity {final String TAG = "MainActivity";ActivityMainBinding activityMainBinding;User user;TwoWayBinding twoWayBinding;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);activityMainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);user = new User("gaoting","123456");twoWayBinding = new TwoWayBinding(user);activityMainBinding.setTwoway(twoWayBinding);activityMainBinding.btPrintUser.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Log.i(TAG,"userName="+user.userName+",password="+user.password);}});activityMainBinding.btChangeUser.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {user.userName = "gaotingchange";user.password = "123456change";activityMainBinding.setTwoway(twoWayBinding);}});}}
2.2使用类静态方法的方法
1)举例静态方法
package com.gaoting.twowaybinding;public class SexUtil {/*** 将int类型的sex转换为中文字符串* @param sex* @return*/public static String getSexString(int sex){if(sex==1){return "男";}else if(sex == 2){return "女";}else if(sex==3){return "taig";}return "外星人";}
}
2)使用Import引入类
<data><variablename="twoway"type="com.gaoting.twowaybinding.TwoWayBinding" /><import type="com.gaoting.twowaybinding.SexUtil"/></data><TextViewandroid:text="@{SexUtil.getSexString(twoway.sex)}"android:id="@+id/tvSexString"android:layout_margin="30dp"android:layout_width="wrap_content"android:layout_height="wrap_content"/>