Android学习笔记-自定义view保存状态

  • android在屏幕切换的时候会对view进行重新绘制,如果没有保存状态的话,之前的输入信息就没有了,对于android自身的控件都有保存状态和回复状态的方法,不过android只保存了在布局文件中有id的控件的状态。
  • 对于自定义的view如果想要保存状态的话需要重写父类的onRestoreInstanceState和onSaveInstanceState方法

下面是我写的一个togglebutton的demo只保存了button的开关状态

//恢复状态
    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if(!(state instanceof SavedState)) {
            super.onRestoreInstanceState(state);
            return;
        }
        SavedState savedState=(SavedState)state;
        super.onRestoreInstanceState(savedState.getSuperState());
        this.status=savedState.status;
    }

    //保存状态
    @Override
    protected Parcelable onSaveInstanceState() {
        Parcelable superState=super.onSaveInstanceState();
        SavedState savedState=new SavedState(superState);
        savedState.status=this.status;
        return savedState;

    }

    public static class SavedState extends BaseSavedState {
      public   boolean status;

        public SavedState(Parcelable superState) {
            super(superState);
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            super.writeToParcel(dest,flags);
            dest.writeByte(this.status ? (byte) 1 : (byte) 0);
        }

        private SavedState(Parcel in) {
            super(in);
            this.status = in.readByte() != 0;
        }

        public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
            @Override
            public SavedState createFromParcel(Parcel source) {
                return new SavedState(source);
            }

            @Override
            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }

最后附上网上看到的view状态保存的流程
Android学习笔记-自定义view保存状态_第1张图片

你可能感兴趣的:(Android,android,控件)