ViewModelSaveState
程序员文章站
2022-03-13 16:46:23
...
记得加上依赖 module的gradle
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation "androidx.lifecycle:lifecycle-viewmodel:2.2.0"
implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:2.3.0-alpha03'
ViewModel类
public class MyViewModel extends ViewModel {
private final SavedStateHandle handle;
public MyViewModel(SavedStateHandle handle) {
this.handle = handle;
}
public MutableLiveData<Integer> getNumber() {
if(!handle.contains(MainActivity.KEY_NUMBER)) {
handle.set(MainActivity.KEY_NUMBER,0);
}
return handle.getLiveData(MainActivity.KEY_NUMBER);
public void add() {
getNumber().setValue(getNumber().getValue() + 1);
}
}
//private MutableLiveData<Integer> number;
// number.setValue(number.getValue() + 1);
// 淘汰
// if(number == null) {
// number = new MutableLiveData<>();
// number.setValue(0);
// }
// return number;
}
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
MyViewModel myViewModel;
public final static String KEY_NUMBER = "my_number";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
myViewModel = new ViewModelProvider(this).get(MyViewModel.class);
binding.setData(myViewModel);
binding.setLifecycleOwner(this);
}
// if(savedInstanceState != null) {
// myViewModel.getNumber().setValue(savedInstanceState.getInt(KEY_NUMBER));
// }
// @Override
// protected void onSaveInstanceState(@NonNull Bundle outState) {
// super.onSaveInstanceState(outState);
// outState.putInt(KEY_NUMBER,myViewModel.getNumber().getValue());
// }
}
上一篇: (递归)整数分解为若干项之和
下一篇: 数分预备篇之第六节
推荐阅读