How Do We Get Data Binding To Use Saved Instance State?

后端 未结 1 1461
隐瞒了意图╮
隐瞒了意图╮ 2021-02-06 07:11

TL;DR: If a layout used with data binding has an EditText, and there is a binding expression for android:text, the binding expression overwrites the sa

相关标签:
1条回答
  • 2021-02-06 07:41

    I thought that ianhanniballake had a reference to a relevant answer, but maybe there is more to it. Here is my interpretation of how that reference can be applied to these circumstances.

    Using the XML that you presented, the following code will alternately restore from the saved instance state and restore from the model. When the saved instance state is restored then, presumably, there is not model instantiated to restore from. That is when mCount is even. If a model exists, then the saved instance state is basically ignored and the binding takes over. There is a little more logic here than we want, but it is less than saving and restoring explicitly.

    mCount is just an artifice for the sake of the argument. A flag or other indication of whether the model exists or not would be used.

    public class MainActivity extends AppCompatActivity {
        private ActivityMainBinding binding;
        private int mCount;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
            mCount = (savedInstanceState == null) ? 0 : savedInstanceState.getInt("mCount", 0);
            if (mCount % 2 == 1) {
                // 1st, 3rd, 5th, etc. rotations. Explicitly execute the bindings and let the framework
                // restore from the saved instance state.
                binding.executePendingBindings();
            } else {
                // First creation and 2nd, 4th, etc. rotations. Set up our model and let the
                // framework restore from the saved instance state then overwrite with the bindings.
                // (Or maybe it just ignores the saved instance state and restores the bindnings.)
                Model model = new Model();
                binding.setModel(model);
            }
            mCount++;
        }
    
        @Override
        public void onSaveInstanceState(Bundle bundle) {
            super.onSaveInstanceState(bundle);
            bundle.putInt("mCount", mCount);
        }
    }
    
    0 讨论(0)
提交回复
热议问题