欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ViewModelSaveState

程序员文章站 2022-03-13 16:46:23
...

ViewModelSaveState
记得加上依赖 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'

ViewModelSaveState
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());
//    }
}
相关标签: Android