編輯:關於 Android 程式設計
終於要談談 Activity 的布局加載流程了。大家都知道,在 Android 體系中,Activity 扮演著界面展示的角色,這也是它與另一個重要組件 Service 最大的不同。但這個界面展示的功能是 Activity 直接控制的嗎?布局文件是如何加載到內存並被 Activity 管理的?Android 中的 View 又是一個怎樣的概念?加載到內存中的布局文件又是如何被繪製出來的?
要回答這些問題,我們需要先了解 Android 的界面加載與繪製流程。本篇我們先學習 Activity 的布局加載流程,至於布局繪製流程,留待下一篇再介紹。
其實,Activity 對界面布局的管理都是通過 Window 對象來實現的。Window 顧名思義就是一個窗口對象,而從用戶角度看,每個 Activity 就是一個個窗口實例。因此不難想象,每個 Activity 中都對應著一個 Window 對象,由它負責加載顯示界面;而 Window 展示不同界面的方式,則是通過定義不同的 View 組件來實現的。
廢話不多說,不知道大家是否還記得我們講過的 Activity 啟動流程。這裡先看一下它的具體實現:
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) { unscheduleGcIdler(); mSomeActivitiesChanged = true; if (r.profilerInfo != null) { mProfiler.setProfiler(r.profilerInfo); mProfiler.startProfiling(); } handleConfigurationChanged(null, null); WindowManagerGlobal.initialize(); Activity a = performLaunchActivity(r, customIntent); if (a != null) { r.createdConfig = new Configuration(mConfiguration); Bundle oldState = r.state; handleResumeActivity(r.token, false, r.isForward, !r.activity.mFinished && !r.startsNotResumed); ... } else { try { ActivityManagerNative.getDefault() .finishActivity(r.token, Activity.RESULT_CANCELED, null, false); } catch (RemoteException ex) { } } }
可以發現,handleLaunchActivity 內部調用了 performLaunchActivity,這才是真正啟動 Activity 的方法。我們來看它的具體實現邏輯:
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) { ... Activity activity = null; try { java.lang.ClassLoader cl = r.packageInfo.getClassLoader(); activity = mInstrumentation.newActivity( cl, component.getClassName(), r.intent); StrictMode.incrementExpectedActivityCount(activity.getClass()); r.intent.setExtrasClassLoader(cl); r.intent.prepareToEnterProcess(); if (r.state != null) { r.state.setClassLoader(cl); } } catch (Exception e) { if (!mInstrumentation.onException(activity, e)) { throw new RuntimeException( "Unable to instantiate activity " + component + ": " + e.toString(), e); } } ... Application app = r.packageInfo.makeApplication(false, mInstrumentation); ... if (activity != null) { Context appContext = createBaseContextForActivity(r, activity); CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager()); Configuration config = new Configuration(mCompatConfiguration); activity.attach(appContext, this, getInstrumentation(), r.token, r.ident, app, r.intent, r.activityInfo, title, r.parent, r.embeddedID, r.lastNonConfigurationInstances, config, r.referrer, r.voiceInteractor); ... return activity; }
從代碼可以看到,這裡通過反射機制創建了 Activity,並調用了 Activity 的 attach 方法。那麼 attach 方法做了什麼呢?我們繼續看它的實現邏輯:
final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token, int ident, Application application, Intent intent, ActivityInfo info, CharSequence title, Activity parent, String id, NonConfigurationInstances lastNonConfigurationInstances, Configuration config, String referrer, IVoiceInteractor voiceInteractor) { attachBaseContext(context); mFragments.attachHost(null /*parent*/); mWindow = new PhoneWindow(this); mWindow.setCallback(this); mWindow.setOnWindowDismissedCallback(this); mWindow.getLayoutInflater().setPrivateFactory(this); if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) { mWindow.setSoftInputMode(info.softInputMode); } if (info.uiOptions != 0) { mWindow.setUiOptions(info.uiOptions); } mUiThread = Thread.currentThread(); mMainThread = aThread; mInstrumentation = instr; mToken = token; mIdent = ident; mApplication = application; mIntent = intent; mReferrer = referrer; mComponent = intent.getComponent(); mActivityInfo = info; mTitle = title; mParent = parent; mEmbeddedID = id; mLastNonConfigurationInstances = lastNonConfigurationInstances; ... mWindow.setWindowManager( (WindowManager)context.getSystemService(Context.WINDOW_SERVICE), mToken, mComponent.flattenToString(), (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0); if (mParent != null) { mWindow.setContainer(mParent.getWindow()); } mWindowManager = mWindow.getWindowManager(); mCurrentConfig = config; }
可以看到,attach 方法在這裡初始化了 Activity 的一系列成員變量,其中最重要的是 mWindow 對象,而且它的實例是 PhoneWindow。這也從側面印證了「一個 Activity 對應一個 Window 對象」。除了 Window,還初始化了其它成員變量,這裡不再展開。回到 performLaunchActivity,在調用 attach 之後又執行了:
mInstrumentation.callActivityOnCreate(activity, r.state);
這裡的 mInstrumentation 是 Instrumentation 類的實例。每個應用進程對應一個 Instrumentation 和一個 ActivityThread,Instrumentation 負責具體調用 Activity 並觸發其生命週期方法。我們來看它的 callActivityOnCreate:
public void callActivityOnCreate(Activity activity, Bundle icicle) { prePerformCreate(activity); activity.performCreate(icicle); postPerformCreate(activity); }
代碼很簡潔,prePerformCreate 與 postPerformCreate 暫且不論,主要邏輯是調用了 activity.performCreate。我們來看 Activity 的 performCreate:
final void performCreate(Bundle icicle) { onCreate(icicle); mActivityTransitionState.readState(icicle); performCreateCommon(); }
原來 onCreate 生命週期方法是在這裡被回調的。前面幾篇文章已對此有過講述,這裡不再贅述。
至此,流程便回調到了我們自己的 Activity 的 onCreate 方法。大家平時重寫 onCreate 時是怎麼加載布局文件的呢?看看典型的寫法:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }
無論怎麼變化,onCreate 一般都是這兩句話。那它們分別是什麼含義呢?先看 super.onCreate。由於我們的 Activity 繼承自 Activity,這裡的 super.onCreate 調用的就是 Activity.onCreate。我們來看它的實現:
protected void onCreate(@Nullable Bundle savedInstanceState) { if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState); if (mLastNonConfigurationInstances != null) { mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders); } if (mActivityInfo.parentActivityName != null) { if (mActionBar == null) { mEnableDefaultActionBarUp = true; } else { mActionBar.setDefaultDisplayHomeAsUpEnabled(true); } } if (savedInstanceState != null) { Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG); mFragments.restoreAllState(p, mLastNonConfigurationInstances != null ? mLastNonConfigurationInstances.fragments : null); } mFragments.dispatchCreate(); getApplication().dispatchActivityCreated(this, savedInstanceState); if (mVoiceInteractor != null) { mVoiceInteractor.attachActivity(this); } mCalled = true; }
可以看到,Activity 的 onCreate 主要做了一些初始化操作。那如果我們在自己的 Activity 中不調用 super.onCreate 會怎樣呢?試過之後,Android Studio 會直接報錯……
FATAL EXCEPTION: main Process: com.example.aaron.helloworld, PID: 18001 android.util.SuperNotCalledException: Activity {com.example.aaron.helloworld/com.example.aaron.helloworld.SecondActivity} did not call through to super.onCreate() at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2422) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2528) ...
可以看到,若不調用 super.onCreate,會在 Activity 的 performLaunchActivity 中報錯。而 performLaunchActivity 正是啟動 Activity 時回調的方法。我們在方法體裡找找拋出的 Exception:
activity.mCalled = false; if (r.isPersistable()) { mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); } else { mInstrumentation.callActivityOnCreate(activity, r.state); } if (!activity.mCalled) { throw new SuperNotCalledException( "Activity " + r.intent.getComponent().toShortString() + " did not call through to super.onCreate()"); }
在 performLaunchActivity 中,調用完 onCreate 之後會有一個判斷:若 Activity 的 mCalled 為 false,就拋出剛才捕獲的異常。那 mCalled 是在哪裡被賦值的呢?正是在 Activity 的 onCreate 方法中。所以我們實現自己的 Activity 時,必須調用 super.onCreate,否則就會拋出這個異常。反過來說,自定義 Activity 一定要在 onCreate 中調用 super.onCreate。
接著看 onCreate 中的 setContentView。它的參數是一個布局文件,而這裡調用的正是 Activity 的 setContentView。我們來看它的實現:
public void setContentView(@LayoutRes int layoutResID) { getWindow().setContentView(layoutResID); initWindowDecorActionBar(); }
這裡的 getWindow 就是獲取 Activity 的 mWindow 成員變量。前面在 attach 方法中我們知道 mWindow 的實例是 PhoneWindow,所以這裡實際調用的是 PhoneWindow 的 setContentView。我們來看它的實現:
@Override public void setContentView(int layoutResID) { if (mContentParent == null) { installDecor(); } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) { mContentParent.removeAllViews(); } if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) { final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID, getContext()); transitionTo(newScene); } else { mLayoutInflater.inflate(layoutResID, mContentParent); } mContentParent.requestApplyInsets(); final Callback cb = getCallback(); if (cb != null && !isDestroyed()) { cb.onContentChanged(); } }
這裡的 mContentParent 是一個 View 對象。由於第一次它為空,所以會執行 installDecor。我們來看 installDecor 的實現:
private void installDecor() { if (mDecor == null) { mDecor = generateDecor(); mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); mDecor.setIsRootNamespace(true); if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) { mDecor.postOnAnimation(mInvalidatePanelMenuRunnable); } } ... }
這裡的 mDecor 是一個 DecorView 對象,而 DecorView 繼承自 FrameLayout,所以 mDecor 本質上是一個 FrameLayout,並通過 generateDecor() 初始化。我們來看 generateDecor:
protected DecorView generateDecor() { return new DecorView(getContext(), -1); }
就是通過 new 創建了一個 DecorView 對象。繼續看 installDecor 的剩餘部分:
if (mContentParent == null) { mContentParent = generateLayout(mDecor);
這裡初始化了 mContentParent 對象,調用了 generateLayout 方法。我們來看它的具體實現:
protected ViewGroup generateLayout(DecorView decor) { ... int layoutResource; int features = getLocalFeatures(); if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) { layoutResource = R.layout.screen_swipe_dismiss; } else if (...) { ... } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) { ... } else { layoutResource = R.layout.screen_simple; } mDecor.startChanging(); View in = mLayoutInflater.inflate(layoutResource, null); decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); mContentRoot = (ViewGroup) in; ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT); if (contentParent == null) { throw new RuntimeException("Window couldn't find content container view"); } ... mDecor.finishChanging(); return contentParent; }
可以發現,這裡正是通過 LayoutInflater.inflate 方法將布局文件加載到內存中的。通過對代碼的分析,我們還發現了 PhoneWindow 中幾個成員變量的關係:
mDecor –> mContentRoot –> mContentParent(包含關係)
我們來看一個典型的布局文件:
<LinearLayout android:fitsSystemWindows="true" android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android="https://schemas.android.com/apk/res/android"> <ViewStub android:id="@+id/action_mode_bar_stub" android:inflatedId="@+id/action_mode_bar" android:layout="@layout/action_mode_bar" android:layout_height="wrap_content" android:layout_width="match_parent" android:theme="?attr/actionBarTheme"> <FrameLayout android:foreground="?android:attr/windowContentOverlay" android:foregroundgravity="fill_horizontal|top" android:foregroundInsidePadding="false" android:id="@android:id/content" android:layout_height="match_parent" android:layout_width="match_parent"> </FrameLayout> </ViewStub> </LinearLayout>
這就是 Activity 加載的根布局文件 screen_simple.xml,其中 ViewStub 對應 Activity 的 titleBar,而 FrameLayout 則主要用於填充內容。
接著我們具體看 LayoutInflater.inflate 方法:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) { return inflate(resource, root, root != null); }
它調用了 inflate 的重載方法:
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) { synchronized (mConstructorArgs) { Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate"); final Context inflaterContext = mContext; final AttributeSet attrs = Xml.asAttributeSet(parser); Context lastContext = (Context) mConstructorArgs[0]; mConstructorArgs[0] = inflaterContext; View result = root; try { int type; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { } if (type != XmlPullParser.START_TAG) { throw new InflateException(parser.getPositionDescription() + ": No start tag found!"); } final String name = parser.getName(); if (TAG_MERGE.equals(name)) { if (root == null || !attachToRoot) { throw new InflateException("<merge> can be used only with a valid ViewGroup root and attachToRoot=true"); } rInflate(parser, root, inflaterContext, attrs, false); } else { final View temp = createViewFromTag(root, name, inflaterContext, attrs); ViewGroup.LayoutParams params = null; if (root != null) { params = root.generateLayoutParams(attrs); if (!attachToRoot) { temp.setLayoutParams(params); } } rInflateChildren(parser, temp, attrs, true); if (root != null && attachToRoot) { root.addView(temp, params); } if (root == null || !attachToRoot) { result = temp; } } } catch (XmlPullParserException e) { InflateException ex = new InflateException(e.getMessage()); ex.initCause(e); throw ex; } catch (Exception e) { InflateException ex = new InflateException( parser.getPositionDescription() + ": " + e.getMessage()); ex.initCause(e); throw ex; } finally { mConstructorArgs[0] = lastContext; mConstructorArgs[1] = null; } Trace.traceEnd(Trace.TRACE_TAG_VIEW); return result; } }
通過分析源碼不難發現,它主要是通過循環解析 XML 文件,將信息解析到內存的 View 對象中。布局文件裡定義的一個個組件被順序解析到內存,並以父子 View 的形式組織起來。這樣,只要給定一個 root View,就能把整個布局文件中定義的組件全部解析出來。
分析完布局解析,回到 setContentView 方法。在調用 installDecor 之後,又執行了:
mLayoutInflater.inflate(layoutResID, mContentParent);
這個方法的含義是:把我們傳入的 layoutId 對應的布局文件,作為 mContentParent 的子 View 加載到內存中。這樣,我們的 layoutId 成為 mContentParent 的子 View,mContentParent 又是 mContentRoot 的子 View,mContentRoot 又是 mDecor 的子 View。通過 LayoutInflater 的 inflate 方法層層加載到內存中,而 Activity 又持有自身 PhoneWindow 的引用,這就相當於 Activity 間接持有了我們定義的布局文件的引用,於是 Activity 的布局文件便被加載到了內存中。
總結:
Activity 展示界面的特性是通過 Window 對象來控制的。
每個 Activity 都對應一個 Window 對象,且 Window 對象的初始化在啟動 Activity 時完成,即在執行 onCreate 之前。
每個 Window 對象內部都存在一個 FrameLayout 類型的 mDecor 對象,它是 Activity 界面的根 View。
Activity 的 Window 實例是 PhoneWindow,其中的 mDecor、mContentRoot、mContentParent 都是 View 組件,關係為:mDecor –> mContentRoot –> mContentParent –> 自定義 layoutView。
LayoutInflater.inflate 主要用於將布局文件加載到內存的 View 組件中,也可以指定加載到某個父組件中。
典型的 onCreate 中需要調用 super.onCreate 和 setContentView:不調用 super.onCreate 會在啟動 Activity 時報錯,不執行 setContentView 則 Activity 只會顯示一個空白頁面。
Android 用 PopupWindow 實作仿微信右上角下拉選單
先來看效果: 這種「點右上角箭頭、下方彈出功能選單」的互動在微信等應用中隨處可見,實作核心就是 PopupWindow 搭配 showAsDropDown()。以下拆解
FloatingActionButton 隨 RecyclerView 捲動淡入淡出的實作
先認識 Promoted Action Promoted Action 指的是一種「主要操作」按鈕,它不放在 ActionBar 裡,而是直接浮在可見的 UI 版面之上(
小米手環怎麼接入微信?開啟步數與排行榜推送
把小米手環接到微信之後,可以直接在微信裡查步數、看排行,不必每次切換 App。設定步驟如下。 先在手机上打开小米手环,点击右上角的「更多」图标。 在選項清單中點擊「服務
Android 自定義 View 實戰:Bitmap 圖像處理與 Matrix 變換全解
一、先認識 Bitmap Bitmap 就是「位圖」,常見副檔名為 .bmp 或 .dib。它是 Windows 平台上最老牌的圖形格式之一,核心概念是把一張圖想成由無數