添加依赖
def lifecycle_version = "2.2.0"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"
activity_view_model_saved_state.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" >
<data>
<variable
name="data"
type="com.jsecode.qnsmw.SavedStateViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="147dp"
android:layout_marginTop="314dp"
android:text="@string/btn_add"
android:onClick="@{()->data.add()}"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView2"
android:layout_width="21dp"
android:layout_height="19dp"
android:layout_marginStart="180dp"
android:layout_marginTop="128dp"
android:text="@{data.number.toString()}"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
SavedStateViewModel.java
private SavedStateHandle handle;
public SavedStateViewModel(SavedStateHandle handle) {
this.handle = handle;
}
public MutableLiveData<Integer> getNumber() {
if (!handle.contains(ViewModelSavedStateActivity.KEY_NUMBER)) {
handle.set(ViewModelSavedStateActivity.KEY_NUMBER, 0);
}
return this.handle.getLiveData(ViewModelSavedStateActivity.KEY_NUMBER);
}
public void add() {
getNumber().setValue(getNumber().getValue() + 1);
}
}
ViewModelSavedStateActivity.java
public class ViewModelSavedStateActivity extends AppCompatActivity {
public static final String KEY_NUMBER = "number";
ActivityViewModelSavedStateBinding binding;
SavedStateViewModel viewModel;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_view_model_saved_state);
ViewModelProvider viewModelProvider = new ViewModelProvider(this,new SavedStateViewModelFactory(getApplication(),this));
viewModel = viewModelProvider.get(SavedStateViewModel.class);
binding.setData(viewModel);
binding.setLifecycleOwner(this);
}
}
网友评论