How to prevent custom views from losing state across screen orientation changes

后端 未结 9 1083
时光说笑
时光说笑 2020-11-22 10:11

I\'ve successfully implemented onRetainNonConfigurationInstance() for my main Activity to save and restore certain critical components across screen orientation

9条回答
  •  佛祖请我去吃肉
    2020-11-22 11:02

    I think this is a much simpler version. Bundle is a built-in type which implements Parcelable

    public class CustomView extends View
    {
      private int stuff; // stuff
    
      @Override
      public Parcelable onSaveInstanceState()
      {
        Bundle bundle = new Bundle();
        bundle.putParcelable("superState", super.onSaveInstanceState());
        bundle.putInt("stuff", this.stuff); // ... save stuff 
        return bundle;
      }
    
      @Override
      public void onRestoreInstanceState(Parcelable state)
      {
        if (state instanceof Bundle) // implicit null check
        {
          Bundle bundle = (Bundle) state;
          this.stuff = bundle.getInt("stuff"); // ... load stuff
          state = bundle.getParcelable("superState");
        }
        super.onRestoreInstanceState(state);
      }
    }
    

提交回复
热议问题