1.创建页面
public class MainActivity extends AppCompatActivity {
ActivityMainLiveDataBinding viewDataBinding;
Model model;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//绑定页面
viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main_live_data);
//绑定生命周期
viewDataBinding.setLifecycleOwner(this);
//获取model
model = ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication()).create(Model.class);
viewDataBinding.setModel(model);
}
}
2.xml文件
<?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="model"
type="com.melo.app.mvvm.liveData.Model" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="50dp"
android:hint="请输入内容"
android:text="@={model.edtString}" />
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text='@{"输入的内容是:"+model.edtString}' />
</LinearLayout>
</layout>
3.model页面
public class Model extends AndroidViewModel {
MutableLiveData<String> edtString = new MutableLiveData<>("");
public Model(@NonNull Application application) {
super(application);
}
public MutableLiveData<String> getEdtString() {
return edtString;
}
}
就这样一个简单的liveData和databinding的配合使用就搞定了。
这里有点需要说下,android 给我们提供了androidViewModel和AndroidViewModelFactory,所以刚刚demo里面的model直接继承的是androidViewModel,而不是liveData。主要是提供了application,当然若是在livedata 我们不需要application 我们也可以直接继承livedata,如下
public class Model extends ViewModel {
MutableLiveData<String> edtString = new MutableLiveData<>("");
public MutableLiveData<String> getEdtString() {
return edtString;
}
}
创建一个自己的ViewModelProvider.Factory
public class MyViewModelFactory implements ViewModelProvider.Factory {
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
//方法一
// if (modelClass.isAssignableFrom(Model.class)) {
// return (T) new Model();
// } else {
// throw new IllegalArgumentException("Unknown ViewModel class");
// }
//方法二
try {
return modelClass.newInstance();
} catch (Exception e) {
throw new IllegalArgumentException("Unknown ViewModel class");
}
}
}
使用方
// 之前的
// model = ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication()).create(Model.class);
//现在的
ViewModelProvider viewModelProvider = new ViewModelProvider(this, new MyViewModelFactory());
model = viewModelProvider.get(Model.class);
网友评论