How to keep user inputs on screen orientation change with Android DataBinding library?

前端 未结 3 1081
不思量自难忘°
不思量自难忘° 2020-12-29 15:09

I\'m at the very beginning of a new Android project. After playing around with MVP in my last project, I want to implement MVVM with Data Binding this time.

I have a

3条回答
  •  Happy的楠姐
    2020-12-29 15:51

    You need to save state of your view model by overriding of method onSaveInstanceState()in your activity class and restore it in onCreate() method.

    private static final String QUESTION = "testViewModel.question";
    private TestViewModel mTestViewModel;
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityTestBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_test);
    
        mTestViewModel = new TestViewModel();
        // Check whether we're recreating a previously destroyed instance
        if (savedInstanceState != null) {
             // restore view model state
             String questionVal = savedInstanceState.getString(QUESTION, "");
             mTestViewModel.setQuestion(questionVal);
        }
        binding.setVm(mTestViewModel);
    }
    
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save current view model state
        savedInstanceState.putString(QUESTION, mTestViewModel.getQuestion());
    
        // Always call the superclass so it can save the view hierarchy state
        super.onSaveInstanceState(savedInstanceState);
    }
    

    More information about "save-restore" technology you can read at this part of documentation

提交回复
热议问题