在上篇文章中我們學習了setContentView的原始碼,還記得其中的LayoutInflater嗎?本篇文章就來學習下LayoutInflater。
@Override
public void setContentView(int resId) {
ensureSubDecor();
ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
contentParent.removeAllViews();
LayoutInflater.from(mContext).inflate(resId, contentParent);
mOriginalWindowCallback.onContentChanged();
}
複製程式碼
備註:本文基於 Android 8.1.0。
1、LayoutInflater 簡介
Instantiates a layout XML file into its corresponding View objects. It is never used directly. Instead, use Activity.getLayoutInflater() or Context.getSystemService(Class) 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.
翻譯過來就是:LayoutInflater 的作用就是將XML佈局檔案例項化為相應的 View 物件,需要通過Activity.getLayoutInflater() 或 Context.getSystemService(Class) 來獲取與當前Context已經關聯且正確配置的標準LayoutInflater。
總共有三種方法來獲取 LayoutInflater:
- Activity.getLayoutInflater();
- Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ;
- LayoutInflater.from(context);
事實上,這三種方法之間是有關聯的:
- Activity.getLayoutInflater() 最終會呼叫到 PhoneWindow 的構造方法,實際上最終呼叫的就是方法三;
- 而方法三最終會呼叫到方法二 Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ;
2、inflate 方法解析
LayoutInflater 的 inflate 方法總共有四個,屬於過載的關係,最終都會呼叫到 inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) 方法。
備註:以下原始碼中有七條備註。
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 {
// Look for the root node.
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();
if (TAG_MERGE.equals(name)) {
// ② 如果是Merge標籤,則必須依附於一個RootView,否則丟擲異常
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 is the root view that was found in the xml
// ③ 根據節點名來建立View物件
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// Create layout params that match root, if supplied
// ④ 如果設定的Root不為null,則根據當前標籤的引數生成LayoutParams
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
// ⑤ 如果不是attachToRoot ,則對這個Tag和建立出來的View設定LayoutParams;注意:此處的params只有當被新增到一個Viewz中的時候才會生效;
temp.setLayoutParams(params);
}
}
if (DEBUG) {
System.out.println("-----> start inflating children");
}
// Inflate all children under temp against its context.
// ⑥ inflate children tag
rInflateChildren(parser, temp, attrs, true);
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
if (root != null && attachToRoot) {
// ⑦ 如果Root不為null且是attachToRoot,則新增建立出來的View到Root 中
root.addView(temp, params);
}
// Decide whether to return the root that was passed in or the
// top view found in xml.
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
......
}
return result;
}
}
複製程式碼
備註:根據以上原始碼,我們也可以分析出來 inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) 不同引數值帶來的影響:
- 如果root為null,attachToRoot將失去作用,設定任何值都沒有意義;
- 如果root不為null,attachToRoot設為true,則會給載入的佈局檔案的指定一個父佈局,即root;
- 如果root不為null,attachToRoot設為false,則會將佈局檔案最外層的所有layout屬性進行設定,當該view被新增到父view當中時,這些layout屬性會自動生效;
- 在不設定attachToRoot引數的情況下,如果root不為null,attachToRoot引數預設為true;
3、rInflate 方法解析
以上程式碼中我們還有兩個方法沒有分析:rInflate 和 rInflateChildren ;而 rInflateChildren 實際上是呼叫了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)) {
if (parser.getDepth() == 0) {
// ① 如果這裡出現了include標籤,就會丟擲異常
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 {
// ③ 最重要的方法在這裡,createViewFromTag
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);
// ⑤新增inflate出來的view到parent中
viewGroup.addView(view, params);
}
}
if (pendingRequestFocus) {
parent.restoreDefaultFocus();
}
if (finishInflate) {
// ⑥如果inflate結束,則回撥parent的onFinishInflate方法
parent.onFinishInflate();
}
}
複製程式碼
總結:
- 首先進行View的合理性校驗,include、merge等標籤;
- 通過 createViewFromTag 建立出 View 物件;
- 如果是 ViewGroup,則重複以上步驟;
- add View 到相應的 parent 中;
4、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;
if (mFactory2 != null) {
// ① 有mFactory2,則呼叫mFactory2的onCreateView方法
view = mFactory2.onCreateView(parent, name, context, attrs);
} else if (mFactory != null) {
// ② 有mFactory,則呼叫mFactory的onCreateView方法
view = mFactory.onCreateView(name, context, attrs);
} else {
view = null;
}
if (view == null && mPrivateFactory != null) {
// ③ 有mPrivateFactory,則呼叫mPrivateFactory的onCreateView方法
view = mPrivateFactory.onCreateView(parent, name, context, attrs);
}
if (view == null) {
// ④ 走到這步說明三個Factory都沒有,則開始自己建立View
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;
}
}
複製程式碼
總結:
- createViewFromTag 方法比較簡單,首先嚐試通過 Factory 來建立View;
- 如果沒有 Factory 的話則通過 createView 來建立View;
5、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) {
// Class not found in the cache, see if it's real, and try to add it
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);
}
}
// ① 反射獲取這個View的構造器
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
// ② 快取構造器
sConstructorMap.put(name, constructor);
} else {
// If we have a filter, apply it to cached constructor
if (mFilter != null) {
// Have we seen this name before?
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) {
// Fill in the context if not already within inflation.
mConstructorArgs[0] = mContext;
}
Object[] args = mConstructorArgs;
args[1] = attrs;
// ③ 使用反射建立 View 物件,這樣一個 View 就被建立出來了
final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
// Use the same context when inflating ViewStub later.
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
mConstructorArgs[0] = lastContext;
return view;
} catch (ClassCastException e) {
}
}
複製程式碼
總結:
- createView 方法也比較簡單,通過反射來建立的 View 物件;
6、總結
通過本文我們學習到 LayoutInflater 建立 View的過程,也知道了 inflate 方法不同引數的意義,以及開發中遇到的一些異常在原始碼中的根源。可以看到從佈局中 inflate 一個個具體的 View 的過程其實也很簡單:
- 通過 XML 的 Pull 解析方式獲取 View 的標籤;
- 通過標籤以反射的方式來建立 View 物件;
- 如果是 ViewGroup 的話則會對子 View 遍歷並重復以上步驟,然後 add 到父 View 中;
- 與之相關的幾個方法:inflate ——》 rInflate ——》 createViewFromTag ——》 createView ;
參考
廣告時間
今日頭條各Android客戶端團隊招人火爆進行中,各個級別和應屆實習生都需要,業務增長快、日活高、挑戰大、待遇給力,各位大佬走過路過千萬不要錯過!
本科以上學歷、非頻繁跳槽(如兩年兩跳),歡迎加我的微信詳聊:KOBE8242011