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

前端 未结 3 1080
不思量自难忘°
不思量自难忘° 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条回答
  •  南方客
    南方客 (楼主)
    2020-12-29 15:34

    The correct answer is below, see: https://stackoverflow.com/a/46086436/4848192

    ViewModels should outlive configuration changes.

    With the new architecture components you could easily implement this:

    public class TestViewModel extends ViewModel{
        ...
    }
    

    Then in your Activity#onCreate(...):

    public class MainActivity extends LifecycleActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            ActivityTestBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_test);
    
            ViewModelProvider provider = ViewModelProviders.of(this);
            binding.setVm(provider.get(TestViewModel.class));
        }
    }
    

提交回复
热议问题