18

既存のView実装から独自のViewクラスを派生させ、少しの値を追加して、Viewの状態を意味のある方法で表すいくつかの変数を維持するとします。

ビューが他のビューと同じように(IDが割り当てられている場合)自動的に状態を保存するので、とをオーバーライドするonRestoreInstanceState()と便利ですonSaveInstanceState()

もちろん、基本クラスのそれぞれのメソッドを呼び出す必要があり、状態情報を基本クラスの状態情報と組み合わせる必要があります。

明らかに、そうするための唯一の安全な方法は、キーが混同されないように、スーパークラスParcelableを独自にラップすることです。Parcelable

これでView.BaseSavedState興味深いメソッドがありますが、派生ビューの状態値とともにgetSuperState()基本クラスを格納するだけで、これが実際にどのように価値を追加するのか理解できず、Parcelableそれを返します。Bundle一方、他のシステムコンポーネントは、すべてのInstanceState情報がタイプView.AbsSavedState(たとえばgetSuperState()、呼び出すことができるもの)であることを期待している可能性がありますか?

共有したい経験はありますか?

4

2 に答える 2

15

名前が示すように、Parcelable のインターフェイスをオーバーライドして値を格納する View.BaseSavedState のサブクラスを実装する必要があると思います。

TextView.SavedState は良い例です

public static class SavedState extends BaseSavedState {
    int selStart;
    int selEnd;
    CharSequence text;
    boolean frozenWithFocus;
    CharSequence error;

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

    @Override
    public void writeToParcel(Parcel out, int flags) {
        super.writeToParcel(out, flags);
        out.writeInt(selStart);
        out.writeInt(selEnd);
        out.writeInt(frozenWithFocus ? 1 : 0);
        TextUtils.writeToParcel(text, out, flags);

        if (error == null) {
            out.writeInt(0);
        } else {
            out.writeInt(1);
            TextUtils.writeToParcel(error, out, flags);
        }
    }

    @Override
    public String toString() {
        String str = "TextView.SavedState{"
                + Integer.toHexString(System.identityHashCode(this))
                + " start=" + selStart + " end=" + selEnd;
        if (text != null) {
            str += " text=" + text;
        }
        return str + "}";
    }

    @SuppressWarnings("hiding")
    public static final Parcelable.Creator<SavedState> CREATOR
            = new Parcelable.Creator<SavedState>() {
        public SavedState createFromParcel(Parcel in) {
            return new SavedState(in);
        }

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

    private SavedState(Parcel in) {
        super(in);
        selStart = in.readInt();
        selEnd = in.readInt();
        frozenWithFocus = (in.readInt() != 0);
        text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);

        if (in.readInt() != 0) {
            error = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
        }
    }
}
于 2013-04-24T04:05:56.897 に答える