編輯:關於 Android 程式設計
写了几周代码,我一直在琢磨一个问题:R.layout.xxx_view.xml 这样的布局文件,究竟是怎么被加载进 Android 的 View 层次结构(也就是我们常说的 View 树)里的?一边读源码一边查资料,下面把这条链路的上半段梳理清楚。
我们最早接触到的方法应该就是它了——在 onCreate() 里调用,就能把根布局显示出来。三个重载版本内部做的事情其实一样,都是转交给 Window:
public void setContentView(int layoutResID) {
getWindow().setContentView(layoutResID);
initActionBar();
}
public void setContentView(View view) {
getWindow().setContentView(view);
initActionBar();
}
public void setContentView(View view, ViewGroup.LayoutParams params) {
getWindow().setContentView(view, params);
initActionBar();
}
顺带一提 addContentView():命名上 set 是替换,add 是追加,调用之后原有的 View 层次结构仍然保留,只是又多加了一个 View。
Activity 里有一个 private Window mWindow 字段,由 attach() 方法在 Activity 创建过程中赋值:
mWindow = PolicyManager.makeNewWindow(this); mWindow.setCallback(this);
Window 是一个抽象类,封装了顶层窗口的样式与行为策略,提供了背景、标题栏、默认按键处理等标准 UI 能力。Android 中它唯一的实现是 PhoneWindow,需要窗口时就会 new 一个实例出来。每个 Activity 都关联一个 Window 对象,并在其上绘制 UI;Window 内部还有一个 mDecor 对象,它是整棵 View 树的根。
PolicyManager 采用运行时加载的方式取得策略实现:
public final class PolicyManager {
private static final String POLICY_IMPL_CLASS_NAME =
"com.android.internal.policy.impl.Policy";
private static final IPolicy sPolicy;
static {
Class policyClass = Class.forName(POLICY_IMPL_CLASS_NAME);
sPolicy = (IPolicy) policyClass.newInstance();
}
public static Window makeNewWindow(Context context) {
return sPolicy.makeNewWindow(context);
}
}
而 Policy 的实现非常直白,同时它还预加载了一批 PhoneWindow 相关的类以提升性能:
public Window makeNewWindow(Context context) {
return new PhoneWindow(context);
}
public LayoutInflater makeNewLayoutInflater(Context context) {
return new PhoneLayoutInflater(context);
}
这也解释了为什么 context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) 拿到的总是 PhoneLayoutInflater。
PhoneWindow 里有两个关键成员:mDecor(窗口顶层的 DecorView)和 mContentParent(系统布局中 @android:id/content 对应的容器)。
@Override
public void setContentView(int layoutResID) {
if (mContentParent == null) {
installDecor();
} else {
mContentParent.removeAllViews();
}
mLayoutInflater.inflate(layoutResID, mContentParent);
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}
这里能看出 setContentView 支持重复调用,效果等同于把之前的 View 层次全部丢掉重来。相比之下 addContentView() 少了 removeAllViews(),所以是纯粹的追加。
installDecor() 负责创建 DecorView(一种特殊的 FrameLayout),并通过 generateLayout(mDecor) 初始化 mContentParent,顺带处理标题、ActionBar、分栏 ActionBar 等一系列窗口特性。
generateLayout() 前半段是从当前主题的 TypedArray 中读取属性,再调用 requestFeature()、setFlags() 等方法把窗口风格设置好;后半段则根据最终确定的 features 挑选对应的系统布局文件:
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 (...FEATURE_CUSTOM_TITLE...) {
layoutResource = com.android.internal.R.layout.screen_custom_title;
} else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
layoutResource = com.android.internal.R.layout.screen_title;
// 有 ActionBar 时则是 screen_action_bar
} else {
layoutResource = com.android.internal.R.layout.screen_simple;
}
mDecor.startChanging();
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");
}
...
mDecor.finishChanging();
return contentParent;
无论选哪个系统布局,它们都有一个共同点:包含一个 id 为 @android:id/content 的 FrameLayout,这就是留给应用层的 placeholder,Activity 的布局从这里开始挂载。
<!-- screen_simple.xml -->
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<ViewStub android:id="@+id/action_mode_bar_stub"
android:inflatedId="@+id/action_mode_bar"
android:layout="@layout/action_mode_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout android:id="@android:id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foregroundInsidePadding="false"
android:foregroundGravity="fill_horizontal|top"
android:foreground="?android:attr/windowContentOverlay" />
</LinearLayout>
screen_title.xml 结构类似,只是多了标题栏,并且 content 容器的高度设为 0dip 配 layout_weight="1",用来占满标题栏以下的剩余空间。
到这里,上半段链路就通了:setContentView() → getWindow().setContentView() → installDecor() 建好 DecorView 与 mContentParent → mLayoutInflater.inflate(layoutResID, mContentParent) 把我们的 XML 挂进系统布局。至此,应用自己的 layout 与系统视图层次正式接轨。后半段涉及 LayoutInflater 如何解析 XML、把标签逐个变成 View 对象并组装成树,留待下篇分析。
【Android】仿今日頭條風格的下拉刷新實作筆記
點一下按鈕會自動觸發下拉刷新,也可以用手勢手動刷新;每完成一次刷新,列表就多出一筆資料。整個頁面由四個分頁(Tab)切換組成。 這個效果其實來自導師交代的專案:替本科同
Android Activity 生命週期完整解析
Android Activity 生命週期 Activity 是 Android 應用中的單一畫面。每個 Activity 都有完整的生命週期,系統會依據使用者操作、記憶
[Android] 自定義帶清除按鈕的 EditText 完整實作
帶一鍵清除功能的輸入框,幾乎每個 App 的搜尋欄都會用到。自己實作一次,可以順便把「複合 Drawable」「TextWatcher」「焦點監聽」這三個基礎 API 串
玩轉 Android Drawable:用 XML 畫出圓角與邊框,並解掉 2.x 的圆角 BUG
很久沒更新部落格,很多東西用完就忘,實在該記下來。除了自己複習,也推薦讀者養成寫筆記的習慣——開發 App 時真正用到的知識遠比一開始想像的多,甚至還會中途被派去用別的語