編輯:關於 Android 程式設計
寫 Android 界面久了,總會遇到一些「知其然不知其所以然」的問題:為什麼 requestWindowFeature() 必須寫在 setContentView() 之前?為什麼 setContentView() 塞進去的布局,並沒有直接變成窗口的根視圖?答案都藏在 Window 這條繼承鏈裡。
本文基於 Android 4.4 源碼(frameworks/base)展開分析。
源碼位置:frameworks/base/core/java/android/view/Window.java
public abstract class Window {
public static final int FEATURE_OPTIONS_PANEL = 0;
public static final int FEATURE_NO_TITLE = 1;
public static final int FEATURE_PROGRESS = 2;
public static final int FEATURE_LEFT_ICON = 3;
public static final int FEATURE_RIGHT_ICON = 4;
public static final int FEATURE_INDETERMINATE_PROGRESS = 5;
public static final int FEATURE_CONTEXT_MENU = 6;
public static final int FEATURE_CUSTOM_TITLE = 7;
public static final int FEATURE_ACTION_BAR = 8;
public static final int FEATURE_ACTION_BAR_OVERLAY = 9;
public interface Callback {
boolean dispatchKeyEvent(KeyEvent event);
boolean dispatchTouchEvent(MotionEvent event);
boolean dispatchGenericMotionEvent(MotionEvent event);
View onCreatePanelView(int featureId);
boolean onMenuItemSelected(int featureId, MenuItem item);
void onWindowAttributesChanged(WindowManager.LayoutParams attrs);
void onContentChanged();
void onWindowFocusChanged(boolean hasFocus);
void onAttachedToWindow();
void onDetachedFromWindow();
void onPanelClosed(int featureId, Menu menu);
boolean onSearchRequested();
ActionMode onWindowStartingActionMode(ActionMode.Callback callback);
void onActionModeStarted(ActionMode mode);
void onActionModeFinished(ActionMode mode);
}
public void setCallback(Callback callback) { mCallback = callback; }
public void setFlags(int flags, int mask) {
final WindowManager.LayoutParams attrs = getAttributes();
attrs.flags = (attrs.flags & ~mask) | (flags & mask);
mForcedWindowFlags |= mask;
if (mCallback != null) {
mCallback.onWindowAttributesChanged(attrs);
}
}
public abstract void setContentView(int layoutResID);
public boolean requestFeature(int featureId) {
final int flag = 1 << featureId;
mFeatures |= flag;
mLocalFeatures |= flag;
return (mFeatures & flag) != 0;
}
}
Activity 聲明時就實現了 Window.Callback 接口:
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory,
Window.Callback,
KeyEvent.Callback,
OnCreateContextMenuListener,
ComponentCallbacks { ... }
而在 Activity 的 attach() 流程中,會有這麼關鍵的兩行:
mWindow = PolicyManager.makeNewWindow(this); mWindow.setCallback(this);
正是這個回調註冊,讓按鍵事件(dispatchKeyEvent)、觸摸事件(dispatchTouchEvent)、滾動事件(dispatchTrackballEvent)以及菜單、ActionMode、內容變化通知等一整套行為,最終都回到了 Activity 自己身上。這也解釋了為什麼我們在 Activity 裡重寫 onKeyDown、onTouchEvent 就能攔截到窗口級別的事件。
這一批常量決定了 Activity 的「外貌」——標題欄、圖標、進度條、Action Bar 的呈現方式:
FEATURE_OPTIONS_PANEL = 0:功能選項面板,默認使能;FEATURE_NO_TITLE = 1:不顯示標題欄;FEATURE_PROGRESS = 2:在標題欄上顯示條狀加載進度,例如 WebView 載入網頁;FEATURE_LEFT_ICON = 3 / FEATURE_RIGHT_ICON = 4:在標題欄左右側顯示圖標;FEATURE_INDETERMINATE_PROGRESS = 5:圓圈狀的不確定進度指示;FEATURE_CONTEXT_MENU = 6:上下文菜單,相當於 PC 上的右鍵菜單,默認使能;FEATURE_CUSTOM_TITLE = 7:自定義標題欄,不能與其他標題欄相關 Feature 混用;FEATURE_ACTION_BAR = 8 / FEATURE_ACTION_BAR_OVERLAY = 9:啟用 ActionBar 及其浮動覆蓋模式。與之配套的還有一組進度相關常量:PROGRESS_VISIBILITY_ON/OFF、PROGRESS_INDETERMINATE_ON/OFF,以及兩條進度軌的起止值(PROGRESS_START = 0 到 PROGRESS_END = 10000,第二軌 20000 到 30000)。
源碼位置:frameworks/base/policy/src/com/android/internal/policy/impl/PhoneWindow.java
public class PhoneWindow extends Window implements MenuBuilder.Callback {
// 窗口的頂層視圖,包含窗口裝飾
private DecorView mDecor;
// 內容容器:可能是 mDecor 本身,也可能是 mDecor 的子視圖
private ViewGroup mContentParent;
private TextView mTitleView;
private CharSequence mTitle = null;
public PhoneWindow(Context context) {
super(context);
mLayoutInflater = LayoutInflater.from(context);
}
}
幾乎所有手機上的 Activity 窗口,背後都是一個 PhoneWindow 實例。Window 這個抽象類在整個 Android 系統裡只有這一個內置實現。

Window 只是一個抽象概念,PhoneWindow 是它的具體落地,而真正顯示在屏幕上的那棵視圖樹的頂端是 DecorView。DecorView 由 PhoneWindow 持有並負責生成。

每一個應用程序窗口的頂層視圖對象,都關聯著一個 ViewRoot 對象,這層關聯由 WindowManagerService 統一維護。ViewRoot 大致相當於 MVC 中的 Controller,職責有三:
我們在自己的 Activity 裡寫下最熟悉不過的兩行:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
}
跟蹤進去會發現,Activity 只是做了一層轉發:
public final boolean requestWindowFeature(int featureId) {
return getWindow().requestFeature(featureId);
}
public void setContentView(int layoutResID) {
getWindow().setContentView(layoutResID);
}
而 PhoneWindow 裡的實現值得細看:
public boolean requestFeature(int featureId) {
// requestFeature 必須在 setContentView 之前調用
if (mContentParent != null) {
throw new AndroidRuntimeException(
"requestFeature() must be called before adding content");
}
final int features = getFeatures();
// 最終交給父類 Window 處理,只是把標志位或上去
return super.requestFeature(featureId);
}
@Override
public void setContentView(int layoutResID) {
if (mContentParent == null) {
installDecor();
} else {
mContentParent.removeAllViews();
}
mLayoutInflater.inflate(layoutResID, mContentParent);
final Callback cb = getCallback();
if (cb != null) {
cb.onContentChanged();
}
}
至此,「為什麼 requestWindowFeature() 不能寫在 setContentView() 之後」這個問題有了明確答案:setContentView() 一旦執行,mContentParent 就不再為 null,此時再改 Feature 已經無法影響 DecorView 的佈局選擇,於是系統直接拋出 AndroidRuntimeException。
同時也能看出 mContentParent 的含義:它描述一個 DecorView 類型的視圖對象,或者該對象的某個子視圖,用作 UI 容器。當它為 null,說明窗口視圖尚未創建,需要調用 installDecor();否則說明是重新設置內容,此時會先移除原有子視圖。
private void installDecor() {
if (mDecor == null) {
mDecor = generateDecor();
}
if (mContentParent == null) {
mContentParent = generateLayout(mDecor);
mTitleView = (TextView) findViewById(com.android.internal.R.id.title);
if (mTitleView != null) {
if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) {
View titleContainer = findViewById(com.android.internal.R.id.title_container);
if (titleContainer != null) {
titleContainer.setVisibility(View.GONE);
} else {
mTitleView.setVisibility(View.GONE);
}
if (mContentParent instanceof FrameLayout) {
((FrameLayout) mContentParent).setForeground(null);
}
} else {
mTitleView.setText(mTitle);
}
}
}
}
protected DecorView generateDecor() {
return new DecorView(getContext(), -1);
}
private final class DecorView extends FrameLayout implements RootViewSurfaceTaker {
public DecorView(Context context, int featureId) {
super(context);
mFeatureId = featureId;
}
}
generateLayout() 是最能體現「Feature 決定樣式」的地方。它先讀取窗口主題屬性,然後按 Feature 組合挑選不同的佈局資源:
protected ViewGroup generateLayout(DecorView decor) {
TypedArray a = getWindowStyle();
// 讀取主題屬性,逐個轉化為 Feature / Flag
if (a.getBoolean(com.android.internal.R.styleable.Window_windowNoTitle, false)) {
requestFeature(FEATURE_NO_TITLE);
} else if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionBar, false)) {
requestFeature(FEATURE_ACTION_BAR);
}
if (a.getBoolean(com.android.internal.R.styleable.Window_windowFullscreen, false)) {
setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN & (~getForcedWindowFlags()));
}
// ... 其餘 windowTranslucentStatus、windowShowWallpaper 等同理
// 根據 Feature 組合選擇 decor 佈局
int layoutResource;
int features = getLocalFeatures();
if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
layoutResource = com.android.internal.R.layout.screen_title_icons;
removeFeature(FEATURE_ACTION_BAR);
} else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
&& (features & (1 << FEATURE_ACTION_BAR)) == 0) {
layoutResource = com.android.internal.R.layout.screen_progress;
} else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
layoutResource = com.android.internal.R.layout.screen_custom_title;
removeFeature(FEATURE_ACTION_BAR);
} else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
if (mIsFloating) {
layoutResource = com.android.internal.R.layout.screen_title;
} else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
layoutResource = com.android.internal.R.layout.screen_action_bar;
} else {
layoutResource = com.android.internal.R.layout.screen_title;
}
} else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
layoutResource = com.android.internal.R.layout.screen_simple_overlay_action_mode;
} else {
// 無裝飾,最簡單的佈局
layoutResource = com.android.internal.R.layout.screen_simple;
}
// 加載 decor 佈局
View in = mLayoutInflater.inflate(layoutResource, null);
decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
// 定位真正的內容容器
ViewGroup contentParent = (ViewGroup) findViewById(ID_ANDROID_CONTENT);
if (contentParent == null) {
throw new RuntimeException("Window couldn't find content container view");
}
// 標題、背景、前景的最終設置
if (getContainer() == null) {
if (mBackgroundResource != 0) {
decor.setWindowBackground(
getContext().getResources().getDrawable(mBackgroundResource));
}
if (mFrameResource != 0) {
decor.setWindowFrame(
getContext().getResources().getDrawable(mFrameResource));
}
if (mTitle != null) setTitle(mTitle);
setTitleColor(mTitleColor);
}
return contentParent;
}
這段代碼把整條邏輯串了起來:DecorView 並不是空的 FrameLayout,而是由 screen_* 系列佈局 inflate 而來;我們傳給 setContentView() 的布局,最終被塞進 DecorView 裡那個 id 為 android:id/content 的 FrameLayout。這也就是 getWindow().getDecorView() 與 findViewById(android.R.id.content) 的由來。
把整條鏈路串起來就是:
Activity.onCreate() → requestWindowFeature() 設置 Feature 標志位 → setContentView() → PhoneWindow.installDecor() → generateDecor() 創建 DecorView → generateLayout() 依據 Feature 挑選 screen_* 佈局並 inflate → 定位 android:id/content 作為 mContentParent → 把我們的布局 inflate 進去 → 回調 onContentChanged() 通知 Activity。
理解了這條鏈路,很多看似「面試題」的問題都能自己推導出來,例如 requestWindowFeature 的調用時機、全屏與沉浸式標志位的作用層級、以及 ActionBar 與標題欄為何互斥。


Android 性能優化:Splash 頁應該這樣設計
目前 SplashActivity 的設計 如今市面上大多數應用在啟動時都會先進入一個 SplashActivity 作為歡迎頁。為什麼要這樣設計?個人總結有三個優點:
路由器不再滿屏亂碼!自訂Android手機Wi-Fi名稱
想讓路由器清楚辨識自己的手機,可修改Android的hostname。Root後用RE檔案管理器編輯system/build.prop,加入net.hostname=自訂
Android 刮刮樂效果控制項實作分享
本文分享一個以 Android 自定義 View 實作的刮刮卡(刮獎)效果控制項,重點在於用 Canvas 搭配 Xfermode 做出「越刮越透」的視覺,並附上可直接套
Android 如何精準獲取設備運營商
今天接到一個新需求:要給服務器上報設備的運營商名稱。我的第一反應是——連友盟都無法精準統計運營商,我該如何判斷具體是哪家運營商呢?如下圖: 這張圖反映了友盟統計到的用戶