設(shè)置View的id
雖然說(shuō)Data Binding這種分層模式使得我么你對(duì)數(shù)據(jù)的傳遞簡(jiǎn)單明了,一般情況下我們可以不設(shè)置View的id蟀给,不適用findViewById即可對(duì)View進(jìn)行數(shù)據(jù)商業(yè)一系列的操作黎做,不過(guò)有時(shí)候根據(jù)情況我們需要對(duì)某些View設(shè)置id叉跛,但是還是可以不findViewById即可得到該控件的對(duì)象,因?yàn)樵O(shè)置id后ViewDataBinding類(lèi)會(huì)自動(dòng)生成對(duì)應(yīng)的控件對(duì)象蒸殿,如:
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="user" type="com.sunzxyong.User"/>
</data>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.userName}"
android:id="@+id/userName"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.userPassword}"
android:id="@+id/userPassword"/>
</LinearLayout>
</layout>
那么在ViewDataBinding類(lèi)中會(huì)自動(dòng)生成相應(yīng)的控件對(duì)象:
public final TextView userName;
public final TextView userPassword;
這些對(duì)象名和id名是一樣的筷厘,然后我們可以通過(guò):
ActivityMainBinding mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
TextView mTvUserName = mBinding.userName;
TextView mTvPassword = mBinding.userPassword;
即可得到TextView的對(duì)象了,再進(jìn)行后續(xù)操作宏所。酥艳。。
Observable觀察者
我們知道爬骤,Data Binding中如果我們直接修改Model實(shí)體對(duì)象(也就是POJO)中的數(shù)據(jù)充石,這些數(shù)據(jù)并不能直接更新到UI,所以Data Binding給了我們一套很好的通知機(jī)制霞玄,分別有三類(lèi): Observable objects, observable fields, and observable collections骤铃,分別表示觀察對(duì)象、觀察字段溃列、觀察集合劲厌,若相應(yīng)的對(duì)象、字段听隐、集合中數(shù)據(jù)變化時(shí)候补鼻,那么UI將會(huì)自動(dòng)更新數(shù)據(jù)。下面我們一一來(lái)介紹它們的用法:
Observable objects
因?yàn)镺bservable是個(gè)接口雅任,Google為我們提供了一個(gè)BaseObservable類(lèi)风范,我們只要把Model類(lèi)繼承自它就獲得了通知UI更新數(shù)據(jù)的能力了,然后再getter方法上添加Bindable注解沪么,在setter方法中使用notifying提醒UI更新數(shù)據(jù)硼婿。如:
private static class User extends BaseObservable {
private String userName;
private String userPassword;
public User(String userName, String userPassword) {
this.userName = userName;
this.userPassword = userPassword;
}
@Bindable
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
notifyPropertyChanged(BR.userName);
}
@Bindable
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
notifyPropertyChanged(BR.userPassword);
}
}
首先我們需要在getter方法上添加Bindable注解后,Bindable注解會(huì)自動(dòng)生成一個(gè)BR類(lèi)禽车,該類(lèi)位于app module包下寇漫,通過(guò)BR類(lèi)我們?cè)O(shè)置更新的數(shù)據(jù),當(dāng)Model中的數(shù)據(jù)發(fā)生變化時(shí)殉摔,setter方法中的notifyPropertyChanged()就會(huì)通知UI更新數(shù)據(jù)了州胳。
下面我們通過(guò)一個(gè)Demo來(lái)看看效果吧:
原先的User類(lèi):
我們沒(méi)有繼承BaseObservable
public class User {
private String userName;
private String userPassword;
public User(String userName, String userPassword) {
this.userName = userName;
this.userPassword = userPassword;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
}
然后onCreate()方法中代碼為:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
final User user = new User("Sunzxyong", "12345678");
mBinding.setUser(user);
//點(diǎn)擊按鈕改變User的數(shù)據(jù)
mBinding.btn.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(android.view.View v) {
user.setUserName("Hello");
user.setUserPassword("87654321");
}
});
}
效果如下:
我們無(wú)論怎么點(diǎn)擊UI界面上都沒(méi)有更新數(shù)據(jù)。逸月。栓撞。
那么我們把User類(lèi)繼承自BaseObservable:
public class User extends BaseObservable {
private String userName;
private String userPassword;
public User(String userName, String userPassword) {
this.userName = userName;
this.userPassword = userPassword;
}
@Bindable
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
notifyPropertyChanged(BR.userName);
}
@Bindable
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
notifyPropertyChanged(BR.userPassword);
}
onCreate()的代碼還是一樣:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
com.sunzxyong.binding.databinding.ActivityMainBinding mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
final User user = new User("Sunzxyong", "12345678");
mBinding.setUser(user);
mBinding.btn.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(android.view.View v) {
user.setUserName("Hello");
user.setUserPassword("87654321");
}
});
}
效果如下:
可以看到Model中的數(shù)據(jù)更新時(shí)UI界面上的數(shù)據(jù)也同時(shí)更新了。
ObservableFields
我們剛剛介紹的通知UI更新的方法是用User類(lèi)繼承自BaseObservable,然后在getter上添加注解瓤湘、在setter中添加notify方法瓢颅,這感覺(jué)總是有點(diǎn)麻煩,步驟繁瑣弛说,于是挽懦,Google推出ObservableFields類(lèi),使用它我們可以簡(jiǎn)化我們的Model類(lèi)剃浇,如:
public class User{
public final ObservableField<String> userName = new ObservableField<>();
public final ObservableField<String> userPassword = new ObservableField<>();
}
沒(méi)錯(cuò)剛剛那一堆代碼就變成了兩行巾兆,然后通過(guò):
User user = new User();
user.userName.set("sunzxyong");
user.userPassword.set("12345678");
String userName = user.userName.get();
String userPassword = user.userPassword.get();
來(lái)設(shè)置和獲取數(shù)據(jù),這樣就簡(jiǎn)便多了虎囚。于是onCreate()方法中的代碼就變成了這樣:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
final User user = new User();
user.userName.set("sunzxyong");
user.userPassword.set("12345678");
mBinding.setUser(user);
mBinding.btn.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(android.view.View v) {
user.userName.set("hello");
user.userPassword.set("87654321");
}
});
}
我們還是來(lái)看一下效果:
UI還是正常更新數(shù)據(jù)角塑。
當(dāng)然ObservableField<T>中傳入的泛型可以是java中的基本類(lèi)型,當(dāng)然我們還可以使用 ObservableBoolean, ObservableByte, ObservableChar, ObservableShort, ObservableInt, ObservableLong, ObservableFloat, ObservableDouble, ObservableParcelable等具體的類(lèi)型淘讥,效果也和ObservableField<T>是一樣的圃伶,如:
public class User{
public final ObservableField<String> userName = new ObservableField<>();
public final ObservableField<Integer> userPassword = new ObservableField<>();
public final ObservableInt userAge = new ObservableInt();
}
Observable Collections
Google也為我們提供了一些通知類(lèi)型的集合,有這三種:ObservableArrayList<T>蒲列、ObservableArrayMap<K,V>窒朋、ObservableMap<K,V>,它和平場(chǎng)使用的List蝗岖、Map用法一樣侥猩,但是多了通知功能。
我們?cè)趌ayout中的<data>區(qū)域?qū)氚缶涂梢灾苯佑盟说钟?dāng)它內(nèi)部的數(shù)據(jù)發(fā)生改變時(shí)就自動(dòng)會(huì)通知UI界面更新欺劳。如:
<data>
<import type="android.databinding.ObservableMap"/>
<import type="com.sunzxyong.binding.Keys"/>
<variable
name="map"
type="ObservableMap<String,Object>"/>
</data>
......
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{map[Keys.name]}" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{String.valueOf(1+(Integer)map[Keys.age])}" />
我來(lái)看一個(gè)Demo,使用ObservableMap<K,V>铅鲤,當(dāng)map中的數(shù)據(jù)改變時(shí)候同時(shí)也通知了UI界面更新划提。
xml布局為:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<import type="android.databinding.ObservableMap"/>
<import type="com.sunzxyong.binding.Keys"/>
<variable
name="map"
type="ObservableMap<String,Object>"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{map[Keys.name]}" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{String.valueOf(1+(Integer)map[Keys.age])}" />
<Button
android:id="@+id/btn"
android:layout_marginTop="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="changeData" />
</LinearLayout>
</layout>
onCreate()方法:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
final ObservableMap<String, Object> map = new ObservableArrayMap<>();
map.put("name", "sunzxyong");
map.put("age", 22);
mBinding.setMap(map);
mBinding.btn.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(android.view.View v) {
map.put("name","hello");
map.put("age",20);
}
});
Keys類(lèi):
public class Keys{
public static final String name = "name";
public static final String age = "age";
}
效果:
創(chuàng)建Binding類(lèi)
我們將數(shù)據(jù)綁定到xml文件后,Binding類(lèi)是自動(dòng)根據(jù)xml布局文件名生成的(繼承自android.databinding.ViewDataBinding)邢享,我們創(chuàng)建Binding對(duì)象一般有以下幾種方法:
1.直接使用自動(dòng)創(chuàng)建的Binding類(lèi)創(chuàng)建
MyLayoutBinding binding = MyLayoutBinding.inflate(layoutInflater);
MyLayoutBinding binding = MyLayoutBinding.inflate(layoutInflater, viewGroup, false);
- 綁定根布局View
MyLayoutBinding binding = MyLayoutBinding.bind(viewRoot);
- 使用DataBindingUtil創(chuàng)建
ViewDataBinding binding = DataBindingUtil.inflate(LayoutInflater, layoutId,
parent, attachToParent);
ViewDataBinding binding = DataBindingUtil.bindTo(viewRoot, layoutId);
Dynamic Variables動(dòng)態(tài)變量
根據(jù)Google官方文檔:
At times, the specific binding class won’t be known. For example, a >RecyclerView.Adapter operating against arbitrary layouts won’t know the specific >binding class. It still must assign the binding value during the onBindViewHolder(VH, >int).
說(shuō)明在使用ListView鹏往、GridView、RecyclerView的時(shí)候骇塘,由于綁定的類(lèi)不能確定伊履,比如RecyclerView只有在onBindViewHolder()方法中才能確定綁定的Item,所以我們只有在該辦法中動(dòng)態(tài)得到Binding Class(ViewModel)款违、動(dòng)態(tài)綁定數(shù)據(jù)唐瀑。方法是:
- 先創(chuàng)建好一個(gè)item布局,在布局中綁定數(shù)據(jù):
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="user"
type="com.sunzxyong.binding.model.User"/>
</data>
<LinearLayout
...>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.userName}"
android:textSize="20sp"
android:textColor="#ffffff" />
...
</LinearLayout>
</layout>
- 創(chuàng)建ViewHolder時(shí)定義一個(gè)和item布局 對(duì)應(yīng)的Binding 對(duì)象奠货,通過(guò)getter和setter對(duì)這個(gè)Binding對(duì)象操作:
public class BindingHolder extends RecyclerView.ViewHolder {
private RecyclerItemBinding binding;
public BindingHolder(View itemView) {
super(itemView);
}
public RecyclerItemBinding getBinding() {
return binding;
}
public void setBinding(RecyclerItemBinding binding) {
this.binding = binding;
}
}
- 在Adapter中onCreateViewHolder()方法中使用DataBindingUtil.inflate()創(chuàng)建Binding 對(duì)象介褥,然后創(chuàng)建一個(gè)ViewHolder對(duì)象座掘,通過(guò)ViewHolder的set把Binding對(duì)象設(shè)置進(jìn)去:
RecyclerItemBinding mItemBinding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.recycler_item, parent, false);
BindingHolder mHolder = new BindingHolder(mItemBinding.getRoot());
mHolder.setBinding(mItemBinding);//把mItemBinding設(shè)置給ViewHolder
- 在onBindViewHolder()方法中通過(guò)holder的getBinding()方法得到item對(duì)應(yīng)的Binding 對(duì)象递惋,再設(shè)置數(shù)據(jù):
//通過(guò)holder.getBinding()得到Binding Class
User user = users.get(position);
holder.getBinding().setVariable(com.sunzxyong.binding.BR.user,user);
holder.getBinding().executePendingBindings();//立即更新UI
好了Data Binding的高級(jí)用法就講完了柔滔,下一篇我們通過(guò)一個(gè)Demo來(lái)看看怎么整體使用Data Binding。萍虽。睛廊。