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 problem understanding DataBinding correctly when it comes to configuration changes like screen orientation change.
All DataBinding samples out there (all I have found when looking for "android mvvm databinding") have the same problem: When I enter something in an EditText and rotate the screen, the EditText is empty afterwards.
As soon as I have something like the following in my layout, I can't get the views (EditText in this case) to restore their state after screen rotation change.
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="vm"
type="com.example.app.TestViewModel" />
</data>
<EditText android:id="@+id/question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@={vm.question}"
android:hint="Question" />
</layout>
I guess this is because of assigning a new view model instance in the activities onCreate method every time.
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityTestBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_test);
binding.setVm(new TestViewModel());
}
How do you handle that correctly?
I can't develop an app with several forms that forget all user inputs at screen orientation.