LiveData在單獨(dú)使用時(shí)蔓彩,想要在數(shù)據(jù)變化時(shí)通知View需要設(shè)置一個(gè)監(jiān)聽
liveData.observe(this, new Observer<String>() {
@Override
public void onChanged(String s) {
}
});
而我們通常是在ViewModel中持有LiveData的引導(dǎo)治笨,而ViewModel中不能持有View的引用,這就很糾結(jié)赤嚼。查閱官方文檔了解到旷赖。從Android Studio3.1開始,支持DataBinding自動(dòng)綁定ViewModel更卒。這樣在數(shù)據(jù)變化時(shí)等孵,就不用手動(dòng)設(shè)置監(jiān)聽來(lái)對(duì)View進(jìn)行相應(yīng)的變化。
下面講下要怎么做
首先定義一個(gè)ViewModel持有LiveData
public class MyViewModel extends ViewModel {
MutableLiveData<String> liveData;
public MutableLiveData<String> getName() {
if (liveData == null) {
liveData = new MutableLiveData<>();
}
return liveData;
}
public void setName(String name) {
if (liveData == null) {
liveData = new MutableLiveData<>();
}
liveData.setValue(name);
}
}
在Activity的OnCreate中初始化
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
MyViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setLifecycleOwner(this);
binding.setMainActivity(this);
viewModel = ViewModelProviders.of(this).get(MyViewModel.class);
viewModel.setName("aaa");
binding.setViewModel(viewModel);
}
public void onButtonClick() {
viewModel.setName("bbb");
}
}
這里給binding設(shè)置了一個(gè)LifecycleOwner蹂空「┟龋可以想象到binding內(nèi)部使用這個(gè)LifecycleOwner給liveData設(shè)置了監(jiān)聽。
在xml中
<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"
tools:context=".MainActivity">
<data>
<variable
name="MainActivity"
type="com.qianfanyun.databinding.MainActivity" />
<variable
name="viewModel"
type="com.qianfanyun.databinding.MyViewModel"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<Button
android:id="@+id/button"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="@={viewModel.name}"
android:onClick="@{()->MainActivity.onButtonClick()}"
/>
</LinearLayout>
</layout>
這里給Button設(shè)置了一個(gè)點(diǎn)擊事件上枕,點(diǎn)擊后會(huì)改變liveData的值咐熙,然后會(huì)發(fā)現(xiàn)Button的text變成了bbb。說(shuō)明綁定成功了辨萍。