該文章為本人試圖進階Android 中高級之路的第三篇常識解讀源碼,后續計劃還有Activity 啟動流程源碼分析 等。該篇文章源碼較多,如果時間允許會記錄一些相關知識點 面試題。該篇閱讀時間:三十分鐘 ,Android SDK 版本:9.0 。另重申 此為學習筆記如有不足,請多指教。
update time : 2019年12月25日19:25:42
前言
以前的兩篇源碼的文章,HashMap 和 Handler 源碼都是相對比較簡單的。本人的學習路線也是提前 半個月進行規劃和確定,所以前邊文章的 基礎Java 和 基礎Android 知識 到后邊的 Android 面試知識進階 到現在的 源碼解讀 也是一個循序漸進 越來越難的過程。那么該篇主要對對查看解讀setContentView()源碼過程的一個學習總結/筆記。
該篇文章篇幅和個人時間問題暫時只記錄到 LayoutInflater層, 算是一個 最簡單的 閱讀源碼的過程,下一篇文章會從 接著該篇文章繼續嘗試深入閱讀 View的繪制流程 。
大體流程圖
進入正題
1. setContentView()入口
進入setContentView 方法,查看 AppCompatActivity 中的方法
public void setContentView(@LayoutRes int layoutResID) {
this.getDelegate().setContentView(layoutResID);
}
@NonNull
public AppCompatDelegate getDelegate() {
if (this.mDelegate == null) {
this.mDelegate = AppCompatDelegate.create(this, this);
}
return this.mDelegate;
}
上述代碼不多贅述,我們主要看 AppCompatDelegate.create 方法,進入AppCompatDelegate 后發現為abstract ,我們在 對應發現中找到AppCompatDelegate實現類 AppCompatDelegateImpl 。
2.AppCompatDelegateImpl
public void setContentView(View v) {
this.ensureSubDecor();
ViewGroup contentParent = (ViewGroup)this.mSubDecor.findViewById(16908290);
contentParent.removeAllViews();
contentParent.addView(v);
this.mOriginalWindowCallback.onContentChanged();
}
public void setContentView(int resId) {
this.ensureSubDecor();
ViewGroup contentParent = (ViewGroup)this.mSubDecor.findViewById(16908290);
contentParent.removeAllViews();
LayoutInflater.from(this.mContext).inflate(resId, contentParent);
this.mOriginalWindowCallback.onContentChanged();
}
public void setContentView(View v, LayoutParams lp) {
this.ensureSubDecor();
ViewGroup contentParent = (ViewGroup)this.mSubDecor.findViewById(16908290);
contentParent.removeAllViews();
contentParent.addView(v, lp);
this.mOriginalWindowCallback.onContentChanged();
}
上述代碼 我們單獨挑一個 方法說就可以,我這里以setContentView(int) 方法
為例,我們一行一行解讀 其中重點是 LayoutInflater.from(this.mContext).inflate(resId, contentParent); inflate部分代碼請異步該文章第三部分 和 ensureSubDecor()兩個方法
2.1ensureSubDecor
private void ensureSubDecor() {
if (!this.mSubDecorInstalled) {
//下文詳細解讀
this.mSubDecor = this.createSubDecor();
//如布局前安裝了一個標題,現在就把它傳播出去
CharSequence title = this.getTitle();
if (!TextUtils.isEmpty(title)) {
if (this.mDecorContentParent != null) {
this.mDecorContentParent.setWindowTitle(title);
} else if (this.peekSupportActionBar() != null) {
this.peekSupportActionBar().setWindowTitle(title);
} else if (this.mTitleView != null) {
this.mTitleView.setText(title);
}
}
//適配尺寸在設備上,一些參數的初始化
this.applyFixedSizeWindow();
// 一臉懵逼 空方法
this.onSubDecorInstalled(this.mSubDecor);
this.mSubDecorInstalled = true;
AppCompatDelegateImpl.PanelFeatureState st = this.getPanelState(0, false);
if (!this.mIsDestroyed && (st == null || st.menu == null)) {
this.invalidatePanelMenu(108);
}
}
}
上述代碼 部分部分方法的作用已經 在注釋中說明,接下來我們看看 createSubDecor 方法
2.2createSubDecor
private ViewGroup createSubDecor() {
// 獲取系統的TypedArray,系統主題
TypedArray a = this.mContext.obtainStyledAttributes(styleable.AppCompatTheme);
if (!a.hasValue(styleable.AppCompatTheme_windowActionBar)) {
// 如果沒有找到就 報錯并釋放TypedArray對象
a.recycle();
throw new IllegalStateException("You need to use a Theme.AppCompat theme (or descendant) with this activity.");
} else {
// 設置各種 Windows 屬性
if (a.getBoolean(styleable.AppCompatTheme_windowNoTitle, false)) {
// requestWindowFeature 方法下邊 說
this.requestWindowFeature(1);
} else if (a.getBoolean(styleable.AppCompatTheme_windowActionBar, false)) {
this.requestWindowFeature(108);
}
if (a.getBoolean(styleable.AppCompatTheme_windowActionBarOverlay, false)) {
this.requestWindowFeature(109);
}
if (a.getBoolean(styleable.AppCompatTheme_windowActionModeOverlay, false)) {
this.requestWindowFeature(10);
}
// 獲取界面是否是浮動的 應該類似于 Dialog 的判斷
this.mIsFloating = a.getBoolean(styleable.AppCompatTheme_android_windowIsFloating, false);
a.recycle();
// PhoneWindow 是Window的子類 ,在PhoneWindow中完成根布局的準備,也就是創建 DecorView ,下文詳細說明
this.mWindow.getDecorView();
LayoutInflater inflater = LayoutInflater.from(this.mContext);
ViewGroup subDecor = null;
// 下文都是根據標記來決定inflate哪個layout
if (!this.mWindowNoTitle) {
if (this.mIsFloating) {
subDecor = (ViewGroup)inflater.inflate(layout.abc_dialog_title_material, (ViewGroup)null);
this.mHasActionBar = this.mOverlayActionBar = false;
} else if (this.mHasActionBar) {
....
} else {
if (this.mOverlayActionMode) {
subDecor = (ViewGroup)inflater.inflate(layout.abc_screen_simple_overlay_action_mode, (ViewGroup)null);
} else {
subDecor = (ViewGroup)inflater.inflate(layout.abc_screen_simple, (ViewGroup)null);
}
if (VERSION.SDK_INT >= 21) {
ViewCompat.setOnApplyWindowInsetsListener(subDecor, new OnApplyWindowInsetsListener() {
public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
int top = insets.getSystemWindowInsetTop();
int newTop = AppCompatDelegateImpl.this.updateStatusGuard(top);
if (top != newTop) {
insets = insets.replaceSystemWindowInsets(insets.getSystemWindowInsetLeft(), newTop, insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom());
}
return ViewCompat.onApplyWindowInsets(v, insets);
}
});
} else {
((FitWindowsViewGroup)subDecor).setOnFitSystemWindowsListener(new OnFitSystemWindowsListener() {
public void onFitSystemWindows(Rect insets) {
insets.top = AppCompatDelegateImpl.this.updateStatusGuard(insets.top);
}
});
}
}
// 如果viewGroup 最后都沒有被賦值 則報錯
if (subDecor == null) {
throw new IllegalArgumentException(...);
} else {
if (this.mDecorContentParent == null) {
this.mTitleView = (TextView)subDecor.findViewById(id.title);
}
ViewUtils.makeOptionalFitsSystemWindows(subDecor);
ContentFrameLayout contentView = (ContentFrameLayout)subDecor.findViewById(id.action_bar_activity_content);
// 獲取 PhoneWindow中的content布局對象
ViewGroup windowContentView = (ViewGroup)this.mWindow.findViewById(16908290);
if (windowContentView != null) {
while(windowContentView.getChildCount() > 0) {
View child = windowContentView.getChildAt(0);
windowContentView.removeViewAt(0);
contentView.addView(child);
}
windowContentView.setId(-1);
contentView.setId(16908290);
if (windowContentView instanceof FrameLayout) {
((FrameLayout)windowContentView).setForeground((Drawable)null);
}
}
this.mWindow.setContentView(subDecor);
contentView.setAttachListener(new OnAttachListener() {
public void onAttachedFromWindow() {
}
public void onDetachedFromWindow() {
AppCompatDelegateImpl.this.dismissPopups();
}
});
return subDecor;
}
}
}
上述代碼 說明基本都在 注釋中,基本大致流程就是這樣 首先獲取 界面的Theme ,然后通過 mWindow. getDecorView() 設置PhoneWindow 中的 DecorView ,根據不同的標識 設置 屬性。接下來我看 一起看看Window 的 實現類PhoneWindow
3.PhoneWindow
上文中的 mWindow 的 實現類就是 PhoneWindow ,雖然還有一個 MockWindow 也是繼承類,但是MockWindow 更多 是一個 測試類,所以我們主要 解讀 PhoneWindow中相應的方法即可。
@Override
public void setContentView(int layoutResID) {
//根據layout的id加載一個布局,然后通過findViewById(R.id.content)加載出布局中id為content
// 的FrameLayout賦值給mContentParent,并且將該view添加到mDecor(DecorView)中
if (mContentParent == null) {
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
// 不是第一次setContentView 移除掉父容器中所有的view 重新添加
mContentParent.removeAllViews();
}
// 窗口是否需要過渡顯示
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
getContext());
transitionTo(newScene);
} else {
// 核心點,前邊的 源碼也有很多地方 使用inflate 方法,我們下邊跟進
mLayoutInflater.inflate(layoutResID, mContentParent);
}
// mContentParent 本質為 FrameLayout
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
mContentParentExplicitlySet = true;
}
我們知道 mContentParent 底層為 FrameLayout 后,基本可以了解到 界面大體布局機構了。如下圖:
上面的ActionBarContextView是標題,不過有些設置是不會顯示整個標題的,所以這里只是一種情況,下面的id為content的FrameLayout就是這個mContentParent,你通過setContentView方法傳遞的視圖會放到這個id為content的FrameLayout上面,這樣你的Activity就顯示了你寫的布局視圖了,由于第一次創建Activity時mContentParent是空的,所以會走PhoneWindow.installDecor方法。
3.1 installDecor
private void installDecor() {
mForceDecorInstall = false;
// 繼承FrameLayout,是窗口頂級視圖,也就是Activity顯示View的根View,包含一個TitleView和一個ContentView
if (mDecor == null) {// 首次為空
// 創建DecorView(FrameLayout)
mDecor = generateDecor(-1);
...
} else {
mDecor.setWindow(this);
}
if (mContentParent == null) {// 第一次setContentView時為空
// 這個mContentParent就是后面從系統的frameworks\base\core\res\res\layout\目錄下加載出來
// 的layout布局(這個Layout布局加載完成后會添加到mDecor(DecorView)中)中的一個id為content的
// FrameLayout控件,這個FrameLayout控件用來盛放setContentView傳遞進來的View
mContentParent = generateLayout(mDecor);
...
// 判斷是否存在id為decor_content_parent的view(我只看到screen_action_bar.xml這個里面有這個id)
final DecorContentParent decorContentParent = (DecorContentParent) mDecor.findViewById(
R.id.decor_content_parent);
if (decorContentParent != null) {
...
if (mDecorContentParent.getTitle() == null) {
// 設置標題
mDecorContentParent.setWindowTitle(mTitle);
}
...
} else {
// 標題視圖
mTitleView = (TextView) findViewById(R.id.title);
// 有的布局中是沒有id為title的控件的,也就是不顯示標題
if (mTitleView != null) {
// 判斷是否有不顯示標題的特性
if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) {
final View titleContainer = findViewById(R.id.title_container);
if (titleContainer != null) {
titleContainer.setVisibility(View.GONE);
} else {
mTitleView.setVisibility(View.GONE);
}
mContentParent.setForeground(null);
} else {// 顯示標題
mTitleView.setText(mTitle);
}
}
}
// 設置背景
if (mDecor.getBackground() == null && mBackgroundFallbackResource != 0) {
mDecor.setBackgroundFallback(mBackgroundFallbackResource);
}
...
}
}
上文mDecor是DecorView,繼承FrameLayout,也就是Activity顯示View的根View,包含一個TitleView和一個ContentView,也就是上面圖形中的最外層藍色的邊框所指代的視圖,這里第一次加載時也是空的,那么會調用generateDecor函數來創建mDecor (具體通過new DecorView(context, featureId, this, getAttributes())方法創建出來的 DecorView),然后通過generateLayout方法創建mContentParent視圖,創建完成后會設置標題,我們接下來看一下 generateLayout 主要的工作。
3.2 generateLayout
protected ViewGroup generateLayout(DecorView decor) {
...
// 獲取Window的各種屬性來設置flag和參數
TypedArray a = getWindowStyle();
// 根據之前的flag和feature來加載一個layout資源到DecorView中,并把可以作為容器的View返回
// 這個layout布局文件在frameworks\base\core\res\res\layout\目錄下
int layoutResource;
int features = getLocalFeatures();
if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
layoutResource = R.layout.screen_swipe_dismiss;
} else if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
// 是否為 dialog 的判斷
if (mIsFloating) {
...
} else {
layoutResource = R.layout.screen_title_icons;
}
removeFeature(FEATURE_ACTION_BAR);
// System.out.println("Title Icons!");
} else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
&& (features & (1 << FEATURE_ACTION_BAR)) == 0) {
layoutResource = R.layout.screen_progress;
} else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
// mIsFloating 這個表示前邊提到過是否為 dailog的
if (mIsFloating) {
...
} else {
layoutResource = R.layout.screen_custom_title;
}
...
} else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
if (mIsFloating) {
...
} else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
layoutResource = a.getResourceId(
R.styleable.Window_windowActionBarFullscreenDecorLayout,
R.layout.screen_action_bar);
} else {
layoutResource = R.layout.screen_title;
}
// System.out.println("Title!");
} else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
layoutResource = R.layout.screen_simple_overlay_action_mode;
} else {
layoutResource = R.layout.screen_simple;
}
mDecor.startChanging();
// 根據layoutResource(布局id)加載系統中布局文件(Layout)并添加到DecorView中
// 方法內 創建了標題視圖,通過LayoutInflater.inflate加載id為layoutResource的布局文件并賦值給根布局
mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
// contentParent是用來添加Activity中布局的父布局(FrameLayout),并帶有相關主題樣式,就是上面
// 提到的id為content的FrameLayout,返回后會賦值給PhoneWindow中的mContentParent
ViewGroup contentParent = (ViewGroup) findViewById(ID_ANDROID_CONTENT);
if (contentParent == null) {
throw new RuntimeException("Window couldn't find content container view");
}
...
mDecor.finishChanging();
return contentParent;
}
這一部分代碼 主要作用都在 注釋中說的差不多了,根據傳入的 DecorView 對他進行 layout 內容的加載。
這篇文章下半部分主要 引出 LayoutInflater.inflate 這個方法做的事情。
至于View和 ViewRootImpl 部分放到下一篇文章解讀
接下來我們一起 一探究竟 看看LayoutInflater.inflate 如何將XML布局文件實例化為相應的 View 對象
4 LayoutInflater.inflate
Instantiates a layout XML file into its corresponding {@link android.view.View}
objects. It is never used directly. Instead, use
{@link android.app.Activity#getLayoutInflater()} or
{@link Context#getSystemService} to retrieve a standard LayoutInflater instance
that is already hooked up to the current context and correctly configured
for the device you are running on.
翻譯:
將布局XML文件實例化為其相應的{@link android.view.View}
對象。 永遠不要直接使用它。 相反,使用
{@link android.app.Activity#getLayoutInflater()}或
{@link Context#getSystemService}檢索標準LayoutInflater實例
已經連接到當前上下文并已正確配置
對于您正在運行的設備。
通過 上述備注已經可以引申到 LayoutInflater.inflate 如何初始化的幾種方法:
- Activity.getLayoutInflater();
- Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ;
- LayoutInflater.from(context);
通過查看源碼Activity.getLayoutInflater() 最終會調用到 PhoneWindow 的構造方法,實際上最終調用的就是3;而3最終會調用到2 Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ;
那么我們通過 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) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
final String name = parser.getName();
// 如果是Merge標簽,則必須依附于一個RootView,
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 {
// Temp 就是通過方法找到的根view
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
// 如果設置的Root不為null,則根據當前標簽的參數生成LayoutParams
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// 注意:此處的params只有當被添加到一個Viewz中的時候才會生效;
// 如果是null 則設置 params 到 根布局
temp.setLayoutParams(params);
}
}
//為 temp 增加children tag內容
rInflateChildren(parser, temp, attrs, true);
// 如果Root不為null且是attachToRoot,則添加創建出來的View到Root 中
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// 判斷返回 根布局對象
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
final InflateException ie = new InflateException(e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (Exception e) {
final InflateException ie = new InflateException(parser.getPositionDescription()
+ ": " + e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} finally {
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
return result;
}
}
簡單梳理一下上述 代碼
如果root為null,attachToRoot將失去作用,設置任何值都沒有意義;
如果root不為null,attachToRoot為true,則會給加載的布局文件的指定一個父布局,即root;
如果root不為null,attachToRoot為false,則會將布局文件最外層的所有layout屬性進行設置,當該view被添加到父view當中時,這些layout屬性會自動生效;
在不設置attachToRoot參數的情況下,如果root不為null,attachToRoot參數默認為true;
4.1 rInflate
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
final int depth = parser.getDepth();
int type;
boolean pendingRequestFocus = false;
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
final String name = parser.getName();
if (TAG_REQUEST_FOCUS.equals(name)) {
pendingRequestFocus = true;
consumeChildElements(parser);
} else if (TAG_TAG.equals(name)) {
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) {
// 如果這里出現了include標簽,就會拋出異常
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
// 同理如果這里出現了merge標簽,也會拋出異常
throw new InflateException("<merge /> must be the root element");
} else {
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
// 如果當前View是ViewGroup(包裹了別的View)則在此處inflate其所有的子View
rInflateChildren(parser, view, attrs, true);
viewGroup.addView(view, params);
}
}
if (pendingRequestFocus) {
parent.restoreDefaultFocus();
}
if (finishInflate) {
// 回調 父類方法
parent.onFinishInflate();
}
}
在上文代碼中 首先判斷了View 的狀態,并對include、merge標簽是否存在進行判斷,通過createViewFromTag創建出View對象,之后通過 rInflateChildren 和 rInflate 方法 ,如果發現View 為 ViewGroup則不斷地輪訓 將所有的 子view 添加到 根布局下*。
4.2 createViewFromTag
上文 createViewFromTag() 對于我們還是未知的,我們將源碼簡單 剖析一下:
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
// Apply a theme wrapper, if allowed and one is specified.
if (!ignoreThemeAttr) {
final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
final int themeResId = ta.getResourceId(0, 0);
if (themeResId != 0) {
context = new ContextThemeWrapper(context, themeResId);
}
ta.recycle();
}
if (name.equals(TAG_1995)) {
// Let's party like it's 1995!
return new BlinkLayout(context, attrs);
}
try {
View view;
// 接下來的判斷 如果判斷對象存在則調用對應的 onCreateView 方法。
if (mFactory2 != null) {
view = mFactory2.onCreateView(parent, name, context, attrs);
} else if (mFactory != null) {
view = mFactory.onCreateView(name, context, attrs);
} else {
view = null;
}
if (view == null && mPrivateFactory != null) {
// mPrivateFactory 如果不為空則調用 其onCreateView方法
view = mPrivateFactory.onCreateView(parent, name, context, attrs);
}
// 如果前邊幾步判斷后 都沒有復制,則自己創建view
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
if (-1 == name.indexOf('.')) {
// 如果View的name中不包含 '.' 則說明是系統控件,會在接下來的調用鏈在name前面加上 'android.view.'
view = onCreateView(parent, name, attrs);
} else {
// 如果name中包含 '.' 則直接調用createView方法,onCreateView 后續也是調用了createView
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
return view;
} catch (InflateException e) {
throw e;
} catch (ClassNotFoundException e) {
.....
} catch (Exception e) {
.....
}
}
上述主要代碼 都有注釋標注,唯一沒有說明的 便是 createView方法禮拜呢到底是怎么通過 控件名稱 和 AttributeSet 獲取到view 呢?
4.3 createView
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
Constructor<? extends View> constructor = sConstructorMap.get(name);
if (constructor != null && !verifyClassLoader(constructor)) {
constructor = null;
sConstructorMap.remove(name);
}
Class<? extends View> clazz = null;
try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
if (constructor == null) {
// 判斷 緩存
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
if (mFilter != null && clazz != null) {
boolean allowed = mFilter.onLoadClass(clazz);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
}
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
sConstructorMap.put(name, constructor);
} else {
if (mFilter != null) {
Boolean allowedState = mFilterMap.get(name);
if (allowedState == null) {
// New class -- remember whether it is allowed
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
mFilterMap.put(name, allowed);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
} else if (allowedState.equals(Boolean.FALSE)) {
failNotAllowed(name, prefix, attrs);
}
}
}
Object lastContext = mConstructorArgs[0];
if (mConstructorArgs[0] == null) {
mConstructorArgs[0] = mContext;
}
Object[] args = mConstructorArgs;
args[1] = attrs;
// 通過反射 獲取 view
final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
mConstructorArgs[0] = lastContext;
return view;
} catch (NoSuchMethodException e) {
......
} catch (ClassCastException e) {
.....
} catch (ClassNotFoundException e) {
throw e;
} catch (Exception e) {
......
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
看完 上述代碼 基本可以梳理一下 LayoutInflater 中創建View 的過程了,首先通過讀取 XML ,使用 Pull 解析方式獲取 View 的標簽;
通過標簽以反射的方式來創建 View 對象;
如果是 ViewGroup 的話則會對子 View 遍歷并重復以上步驟,然后 add 到父 View 中;
方法順序:inflate -> rInflate -> createViewFromTag-> createView
到這里其實 整個布局 繪制流程已經大概清除了 ,