Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

Android 中正確保存 View 狀態的完整指南

編輯:Android 資訊

本文討論 View 狀態的保存與恢復。之所以特別強調 View,是因為這件事比保存 Activity 或 Fragment 狀態要微妙一些,而網上流傳的方案裡,重複造輪子的情況相當普遍。

為什麼要保存 View 狀態

移動應用應該幫用戶解決問題,而不是製造問題。

想象一個字段眾多的設置頁面:

這個截圖並非典型的移動界面,但足以說明問題:大量輸入框、多選框、開關。你花了十五分鐘填完所有內容,正準備點「完成」,結果不小心轉了屏——所有改動歸零。

總有極少數用戶不介意重填一遍,但我們沒有理由讓他們重填。除非用戶明確要求,否則就該保存。

Android 是如何管理 View 狀態的

先看一個帶圖片、文字與 Switch 的簡單布局:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:padding="@dimen/activity_horizontal_margin">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:layout_width="0dip"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="My Text" />

    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dip" />

</LinearLayout>

滑動一下 switch,然後旋轉屏幕——開關回到了初始狀態。Android 通常會自動保存系統控件的狀態,為什麼這裡失效了?

要回答這個問題,得先看框架的保存與恢復流程:

  • saveHierarchyState(SparseArray<Parcelable> container):框架在需要保存狀態時調用,內部轉調 dispatchSaveInstanceState()。
  • dispatchSaveInstanceState(SparseArray<Parcelable> container):調用 onSaveInstanceState() 取得代表當前狀態的 Parcelable,以「View ID 為鍵、Parcelable 為值」存入 container。若是 ViewGroup,還要遍歷子 View 逐一保存。
  • Parcelable onSaveInstanceState():自定義 View 應重寫此方法,返回真實的狀態對象。
  • restoreHierarchyState(SparseArray<Parcelable> container):恢復時調用,傳入的 container 中裝著保存階段的所有狀態。
  • dispatchRestoreInstanceState(SparseArray<Parcelable> container):按 View ID 找出對應 Parcelable 並交給 onRestoreInstanceState();若是 ViewGroup,同樣要處理子 View。
  • onRestoreInstanceState(Parcelable state):接收屬於自己的那份狀態。

整個流程的關鍵點是:container 在整棵 View 樹中是共享的。這一點決定了後面的所有結論。

既然狀態以 View ID 為鍵存儲,那麼沒有 ID 的 View 就不會被保存;而恢復時也無從判斷某份狀態屬於誰。這正是 switch 失效的原因。

給每個 View 補上 id:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:padding="@dimen/activity_horizontal_margin">

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/text"
        android:layout_width="0dip"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="My Text" />

    <Switch
        android:id="@+id/toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dip" />

</LinearLayout>

此時旋轉屏幕,狀態得以保留。container 的結構如下:

每個 View 都以自己的 id 為鍵,把 Parcelable 存進共享的 SparseArray。我們並沒有提供任何 Parcelable,之所以能工作,是因為框架自己知道如何保存內置控件——Switch 重寫了 onSaveInstanceState()。

除了 id,還需要顯式聲明「我要保存狀態」,即調用 setSaveEnabled(true)。內置控件通常默認已開啟,但從零實現自定義 View 時需要手動設置。

總結成兩條硬性條件:

  1. View 必須有 id;
  2. 必須調用 setSaveEnabled(true)。

保存自定義狀態

現在來看更複雜的情形:在 Switch 的子類上額外掛一份自定義狀態。

public class CustomSwitch extends Switch {

    private int customState;

    public void setCustomState(int customState) {
        this.customState = customState;
    }
}

保存與恢復的完整實現:

public class CustomSwitch extends Switch {

    private int customState;

    public void setCustomState(int customState) {
        this.customState = customState;
    }

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState ss = new SavedState(superState);
        ss.state = customState;
        return ss;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState ss = (SavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());
        setCustomState(ss.state);
    }

    static class SavedState extends BaseSavedState {
        int state;

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

        private SavedState(Parcel in) {
            super(in);
            state = in.readInt();
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeInt(state);
        }

        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];
                    }
                };
    }
}

逐點解釋:

重寫 onSaveInstanceState 後,必須先調用父類實現,讓父類保存它關心的內容。在這個例子裡,Switch 會創建一個 Parcelable 並填入自身狀態。問題是 Parcelable 無法追加字段,因此需要一層封裝——Android 提供的 View.BaseSavedState 正是為此而生:它持有上一級的 superState,同時允許你附加自定義屬性。

恢復時做相反的事:從 Parcelable 中取出上一級狀態,通過 super.onRestoreInstanceState(ss.getSuperState()) 交還父類,最後再恢復自己的字段。

一條鐵律:重寫 onSaveInstanceState 就必須保存父類狀態。

View 的 ID 必須唯一

接下來是一個實戰中極易中招的場景:把一段布局抽成自定義 View 以便復用,然後在同一頁面中 include 兩次。

改動配置之後,狀態全部串味了。看看 SparseArray 裡發生了什麼:

原因很直白:狀態以 view id 為鍵,而 container 在整棵 View 樹中共享。兩個實例的 id 都是 @id/toggle,於是後寫入的覆蓋了先寫入的,container 裡只剩一份。恢復時,兩個 View 拿到同一份狀態。

解法是讓每個容器擁有自己獨立的 SparseArray:

public class MyCustomLayout extends LinearLayout {

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState ss = new SavedState(superState);
        ss.childrenStates = new SparseArray<>();
        for (int i = 0; i < getChildCount(); i++) {
            getChildAt(i).saveHierarchyState(ss.childrenStates);
        }
        return ss;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState ss = (SavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());
        for (int i = 0; i < getChildCount(); i++) {
            getChildAt(i).restoreHierarchyState(ss.childrenStates);
        }
    }

    @Override
    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
        dispatchFreezeSelfOnly(container);
    }

    @Override
    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
        dispatchThawSelfOnly(container);
    }

    static class SavedState extends BaseSavedState {
        SparseArray childrenStates;

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

        private SavedState(Parcel in, ClassLoader classLoader) {
            super(in);
            childrenStates = in.readSparseArray(classLoader);
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeSparseArray(childrenStates);
        }

        public static final ClassLoaderCreator<SavedState> CREATOR =
                new ClassLoaderCreator<SavedState>() {
                    @Override
                    public SavedState createFromParcel(Parcel source, ClassLoader loader) {
                        return new SavedState(source, loader);
                    }

                    @Override
                    public SavedState createFromParcel(Parcel source) {
                        return createFromParcel(source, null);
                    }

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

這段代碼做了五件事:

  • 自定義 SavedState 除了父類狀態,還多持有一個 SparseArray 用於存放子 View 狀態;
  • onSaveInstanceState 中主動遍歷子 View,把狀態寫入這個獨立 container;
  • onRestoreInstanceState 中主動從同一 container 恢復;
  • 重寫 dispatchSaveInstanceState 並調用 dispatchFreezeSelfOnly(),告訴框架「只保存我自己,不要碰子 View」;
  • 重寫 dispatchRestoreInstanceState 並調用 dispatchThawSelfOnly(),恢復邏輯同理。

為什麼需要後兩步?因為 ViewGroup 的默認 dispatch 實現會自動遍歷子 View 並寫入共享 container——如果放任不管,我們剛建立的隔離就被繞過了。這兩個方法正是用來「關掉」默認行為的開關。

最終結構:

每個 view group 各自持有 SparseArray,互不干擾,覆蓋問題消失。

三條可以記住的結論

把整篇文章濃縮成 checklist:

  1. 凡是需要保存狀態的 View,一定要有 id,並確認 setSaveEnabled 為 true;
  2. 自定義狀態通過 BaseSavedState 子類封裝,重寫 onSaveInstanceState 時務必先保存 superState;
  3. 同一 id 在同一棵 View 樹中只能出現一次;若必須復用含 id 的布局,就讓容器隔離自己的子狀態 container。

本文示例代碼可在 GitHub 上找到。理解這套機制之後,配置變更導致的狀態丟失就基本不再是問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved