編輯:關於 Android 程式設計
談到界面狀態的持久化,幾乎每個 Android 開發者都繞不開 Activity#onSaveInstanceState(Bundle)。當 Activity 因為記憶體不足被系統回收、或者使用者切到後台又返回時,系統需要把畫面上那些「使用者看得見的痕跡」——輸入框裡的文字、ScrollView 的位置、CheckBox 的勾選狀態——重新還原回來,靠的就是這套機制。
它的源碼結構其實非常清爽:
private static final String WINDOW_HIERARCHY_TAG = "android:viewHierarchyState";
protected void onSaveInstanceState(Bundle outState) {
// 1、保存整個 Window 的 View 樹狀態
outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());
// 2、保存 Fragment 狀態
Parcelable p = mFragments.saveAllState();
if (p != null) {
outState.putParcelable(FRAGMENTS_TAG, p);
}
getApplication().dispatchActivitySaveInstanceState(this, outState);
}
一句話概括:Activity 的界面由 View 層次樹和 Fragment 兩部分組成,所以保存也分成這兩條線。
入口是 mWindow.saveHierarchyState(),最終落到 PhoneWindow 的實現上:
@Override
public Bundle saveHierarchyState() {
Bundle outState = new Bundle();
if (mContentParent == null) {
return outState;
}
// 所有 View 的狀態都裝進這個 SparseArray
SparseArray<Parcelable> states = new SparseArray<>();
mContentParent.saveHierarchyState(states);
outState.putSparseParcelableArray(VIEWS_TAG, states);
// 記錄焦點 View 的 id
View focusedView = mContentParent.findFocus();
if (focusedView != null && focusedView.getId() != View.NO_ID) {
outState.putInt(FOCUSED_ID_TAG, focusedView.getId());
}
// 保存各類面板與 ActionBar 狀態
SparseArray<Parcelable> panelStates = new SparseArray<>();
savePanelState(panelStates);
if (panelStates.size() > 0) {
outState.putSparseParcelableArray(PANELS_TAG, panelStates);
}
if (mActionBar != null) {
SparseArray<Parcelable> actionBarStates = new SparseArray<>();
mActionBar.saveHierarchyState(actionBarStates);
outState.putSparseParcelableArray(ACTION_BAR_TAG, actionBarStates);
}
return outState;
}
關鍵只有三行:建立一個 SparseArray 容器,交給頂層容器 mContentParent 去遞歸填充,最後掛到 Bundle 上。
mContentParent 是一個 ViewGroup,它並沒有自己實現 saveHierarchyState,而是沿用 View 的版本:
public void saveHierarchyState(SparseArray<Parcelable> container) {
dispatchSaveInstanceState(container);
}
真正的遞歸發生在 ViewGroup 的分發方法裡:
@Override
protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
// 先保存自己
super.dispatchSaveInstanceState(container);
// 再遍歷所有子 View
final int count = mChildrenCount;
final View[] children = mChildren;
for (int i = 0; i < count; i++) {
View c = children[i];
if ((c.mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED) {
c.dispatchSaveInstanceState(container);
}
}
}
邏輯是典型的深度優先遍歷:先處理自己,再讓每個孩子重複同樣的動作。
而每個「葉子」View 的處理在 View 類中:
protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
Parcelable state = onSaveInstanceState();
if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
throw new IllegalStateException(
"Derived class did not call super.onSaveInstanceState()");
}
if (state != null) {
container.put(mID, state);
}
}
}
第一,沒有 id 的 View 不會被保存。因為容器是以 view id 作為 key 的,mID == NO_ID 直接就被跳過了。這也是為什麼自定義控件一定要在布局裡寫 android:id。
第二,自定義 View 若想保存額外資料,重寫 onSaveInstanceState() 時必須調用父類實現,否則會拋出 IllegalStateException——源碼裡那段判斷就是專門用來攔截這種「不守規矩」的子類。
保存下來的 SparseArray 並不由 ViewGroup 自己持有,而是統一塞進 Bundle。因此恢復的第一步是拿回這個 Bundle,而 Activity 的 onCreate(Bundle) 與 onRestoreInstanceState(Bundle) 都能取到它。
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (mWindow != null) {
Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);
if (windowState != null) {
mWindow.restoreHierarchyState(windowState);
}
}
}
PhoneWindow 的實現與保存過程幾乎是鏡像關係:
@Override
public void restoreHierarchyState(Bundle savedInstanceState) {
if (mContentParent == null) {
return;
}
SparseArray<Parcelable> savedStates = savedInstanceState.getSparseParcelableArray(VIEWS_TAG);
if (savedStates != null) {
mContentParent.restoreHierarchyState(savedStates);
}
// 恢復焦點
int focusedViewId = savedInstanceState.getInt(FOCUSED_ID_TAG, View.NO_ID);
if (focusedViewId != View.NO_ID) {
View needsFocus = mContentParent.findViewById(focusedViewId);
if (needsFocus != null) {
needsFocus.requestFocus();
}
}
// 恢復面板與 ActionBar 狀態……
}
ViewGroup 同樣沒有重寫 restoreHierarchyState,它走的是 View 的實現,然後由 dispatchRestoreInstanceState 完成遞歸:
@Override
protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
super.dispatchRestoreInstanceState(container); // 恢復自己
final int count = mChildrenCount;
final View[] children = mChildren;
for (int i = 0; i < count; i++) {
View c = children[i];
if ((c.mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED) {
c.dispatchRestoreInstanceState(container);
}
}
}
最終每個 View 從容器裡按 id 取出属于自己的那份 Parcelable:
protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
if (mID != NO_ID) {
Parcelable state = container.get(mID);
if (state != null) {
mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
onRestoreInstanceState(state);
if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
throw new IllegalStateException(
"Derived class did not call super.onRestoreInstanceState()");
}
}
}
}
所以結論很對稱:重寫了 onSaveInstanceState 就一定要重寫 onRestoreInstanceState,並且兩邊都要調用 super。存與取必須成对出現,否則資料對不上。
回到 Activity 那行 mFragments.saveAllState()。這裡的 mFragments 是 FragmentManagerImpl,它會遍歷所有活躍的 Fragment,為每個 Fragment 生成一個 FragmentState,並把回退棧、已添加列表等資訊一起打包:
Parcelable saveAllState() {
int N = mActive.size();
FragmentState[] active = new FragmentState[N];
for (int i = 0; i < N; i++) {
Fragment f = mActive.get(i);
if (f != null) {
FragmentState fs = new FragmentState(f);
active[i] = fs;
if (f.mState > Fragment.INITIALIZING
&& fs.mSavedFragmentState == null) {
fs.mSavedFragmentState = saveFragmentBasicState(f);
}
}
}
// 收集 mAdded 列表與回退棧 BackStackState[]……
return new FragmentManagerState(active, added, backStack);
}
單個 Fragment 的狀態由 saveFragmentBasicState 負責,值得注意的是它會把 Fragment 內部那棵 View 樹也一併保存:
Bundle saveFragmentBasicState(Fragment f) {
Bundle result = null;
if (mStateBundle == null) {
mStateBundle = new Bundle();
}
f.performSaveInstanceState(mStateBundle);
if (!mStateBundle.isEmpty()) {
result = mStateBundle;
mStateBundle = null;
}
// Fragment 內部的 View 也是一棵 View 樹
if (f.mView != null) {
saveFragmentViewState(f);
}
if (f.mSavedViewState != null) {
if (result == null) {
result = new Bundle();
}
result.putSparseParcelableArray(VIEW_STATE_TAG, f.mSavedViewState);
}
return result;
}
而 saveFragmentViewState 用的正是我們前面分析過的那套遞歸:
void saveFragmentViewState(Fragment f) {
if (f.mView == null) {
return;
}
if (mStateArray == null) {
mStateArray = new SparseArray<Parcelable>();
} else {
mStateArray.clear();
}
f.mView.saveHierarchyState(mStateArray);
if (mStateArray.size() > 0) {
f.mSavedViewState = mStateArray;
mStateArray = null;
}
}
恢復的起點在 Activity 的 onCreate:
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
mFragments.restoreAllState(p,
mLastNonConfigurationInstances != null
? mLastNonConfigurationInstances.fragments : null);
}
}
restoreAllState 會根據保存的 FragmentState 列表重建 Fragment 實例,把它們重新掛回容器,再按記錄逐個恢復視圖狀態與回退棧。這也解釋了一個常見困惑:為什麼 Fragment 明明沒有 new,重啟後卻自己「回來」了——系統幫你重建了。
把上面的源碼鏈路串起來,實戰中只需要記住幾條:
· 需要保存狀態的 View 一定要有唯一 id,且同一層次樹中不能重複。
· 自定義 View 的 save / restore 必須成對重寫,並調用 super。
· 大量二進位資料(如 Bitmap)不要塞進 Bundle,TransactionTooLargeException 往往就是這麼來的,應該只存路徑或引用。
· Fragment 被系統重建時,不要在 onCreate 裡無條件 new 一份再 add,否則會出現重疊;正確做法是用 tag 去 findFragmentByTag 判斷是否已存在。
· 依賴 getActivity() 的異步任務要在 Fragment detach 時取消,避免空指標。
Android RecyclerView 基本用法詳解(含點擊事件實作)
一、什麼是 RecyclerView RecyclerView 主要用於展示並回收 View,官方對它的概括是:一種透過提供有限的可視區域來有效顯示大資料集的檢視。 它提
Android 監聽 EditText 輸入變化:TextWatcher 的兩個實用案例
在 Android 開發中,我們常常需要即時監聽 EditText 的輸入內容變化,例如做字數統計或輸入格式校驗。這可以透過 EditText 的 addTextChan
硅谷商城項目解析:發現模組的 TabLayout、彈幕與 Gson
硅谷商城項目中的發現模組,主要負責內容瀏覽與社群互動。它結合了 TabLayout、彈幕與 Gson,讓頁面切換、動態展示與資料解析更完整。 TabLayout 標題切
Android 開發:使用 PULL 解析與生成 XML
一、使用 PULL 解析 XML1. PULL 簡介除了在〈淺談 XML 解析的幾種方式〉中介紹過的 DOM、SAX、Jdom、dom4j 等解析方式外,Android