Jetpack之ViewModel-SavedState使用教程

1.在Model的Gradle 引入 dataBinding

defaultConfig {
    dataBinding.enabled = true
}

2.添加savedstate依赖库

implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:2.3.0-alpha01'

3.创建MyViewModel类并继承ViewModel

private SavedStateHandle handler;

private final String KEY = "key";

public MyViewModel(SavedStateHandle handler) {
    this.handler = handler;
}

public MutableLiveData 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文件中使用把控件和数据进行绑定



    

5.在MainActivity中将MyViewModel 和activity_main.xml进行关联

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);
}

你可能感兴趣的:(Jetpack之ViewModel-SavedState使用教程)