1.在Model的Gradle 引入 dataBinding
defaultConfig {
dataBinding.enabled = true
}
2.添加savedstate依賴庫
implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:2.3.0-alpha01'
3.創(chuàng)建MyViewModel類并繼承ViewModel
private SavedStateHandle handler;
private final String KEY = "key";
public MyViewModel(SavedStateHandle handler) {
this.handler = handler;
}
public MutableLiveData<Integer> getMutableLiveData() {
if (!this.handler.contains(KEY)) {
this.handler.set(KEY, 0);
}
return this.handler.getLiveData(KEY);
}
public void add() {
getMutableLiveData().setValue(getMutableLiveData().getValue() + 1);
}
4.在activity_main.xml文件中使用把控件和數(shù)據(jù)進(jìn)行綁定
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{()->data.add()}"
android:text="@string/btn_add"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{String.valueOf(data.getMutableLiveData())}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.473"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.235" />
</androidx.constraintlayout.widget.ConstraintLayout>
<data>
<variable
name="data"
type="com.example.myapplication.MyViewModel" />
</data>
5.在MainActivity中將MyViewModel 和activity_main.xml進(jìn)行關(guān)聯(lián)
MyViewModel myViewModel;
ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myViewModel = new ViewModelProvider(this, new SavedStateViewModelFactory(getApplication(), this)).get(MyViewModel.class);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setData(myViewModel);
binding.setLifecycleOwner(this);
}