Android從xml加載到View對(duì)象過程解析
我們從Activity的setContentView()入手,開始源碼解析,
//Activity.setContentView public void setContentView(int layoutResID) { getWindow().setContentView(layoutResID); initActionBar(); } //PhoneWindow.setContentView 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(); } }
發(fā)現(xiàn)是使用mLayoutInflater創(chuàng)建View的,所以我們?nèi)ayoutInflater.inflate()里面看下,
public View inflate(int resource, ViewGroup root, boolean attachToRoot) { if (DEBUG) System.out.println("INFLATING from resource: " + resource); XmlResourceParser parser = getContext().getResources().getLayout(resource); try { return inflate(parser, root, attachToRoot); } finally { parser.close(); } }
先根據(jù)resource id 獲取到XmlResourceParseer,意如其名,就是xml的解析器,繼續(xù)往下,進(jìn)入到inflate的核心方法,有些長(zhǎng),我們只分析關(guān)鍵部分:
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) { ...... 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, attrs, false); } else { // Temp is the root view that was found in the xml View temp; if (TAG_1995.equals(name)) { temp = new BlinkLayout(mContext, attrs); } else { temp = createViewFromTag(root, name, attrs); } ...... } catch (XmlPullParserException e) { InflateException ex = new InflateException(e.getMessage()); ex.initCause(e); throw ex; } catch (IOException e) { InflateException ex = new InflateException( parser.getPositionDescription() + ": " + e.getMessage()); ex.initCause(e); throw ex; } finally { // Don't retain static reference on context. mConstructorArgs[0] = lastContext; mConstructorArgs[1] = null; } return result; } }
如果tag的名字不是TAG_1995(名字是個(gè)梗),就調(diào)用函數(shù)createViewFromTag()創(chuàng)建View,進(jìn)去看看,
View createViewFromTag(View parent, String name, AttributeSet attrs) { if (name.equals("view")) { name = attrs.getAttributeValue(null, "class"); } ...... View view; if (mFactory2 != null) view = mFactory2.onCreateView(parent, name, mContext, attrs); else if (mFactory != null) view = mFactory.onCreateView(name, mContext, attrs); else view = null; if (view == null && mPrivateFactory != null) { view = mPrivateFactory.onCreateView(parent, name, mContext, attrs); } if (view == null) { if (-1 == name.indexOf('.')) { view = onCreateView(parent, name, attrs); } else { view = createView(name, null, attrs); } } if (DEBUG) System.out.println("Created view is: " + view); return view; ...... }
首先嘗試用3個(gè)Fractory創(chuàng)建View,如果成功就直接返回了。注意,我們可以利用這個(gè)機(jī)制,創(chuàng)建自己的Factory來控制View的創(chuàng)建過程。
如果沒有Factory或創(chuàng)建失敗,那么走默認(rèn)邏輯。
先判斷name中是否有'.'字符,如果沒有,則認(rèn)為使用android自己的View,此時(shí)會(huì)在name的前面加上包名"android.view.";如果有這個(gè)'.',則認(rèn)為使用的自定義View,這時(shí)無需添加任何前綴,認(rèn)為name已經(jīng)包含全包名了。
最終,使用這個(gè)全包名的name來創(chuàng)建實(shí)例,
private static final HashMap<String, Constructor<? extends View>> sConstructorMap = new HashMap<String, Constructor<? extends View>>(); protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException { return createView(name, "android.view.", attrs); } public final View createView(String name, String prefix, AttributeSet attrs) throws ClassNotFoundException, InflateException { Constructor<? extends View> constructor = sConstructorMap.get(name); Class<? extends View> clazz = null; ...... 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); } } constructor = clazz.getConstructor(mConstructorSignature); 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[] args = mConstructorArgs; args[1] = attrs; return constructor.newInstance(args); ...... }
從源碼中看到,在創(chuàng)建實(shí)例前,會(huì)先從一個(gè)靜態(tài)Map中獲取緩存,
Constructor<? extends View> constructor = sConstructorMap.get(name);
緩存的是Constructor對(duì)象,目的是用于創(chuàng)建實(shí)例,這里要注意sConstructorMap是靜態(tài)的,并且通過Constructor創(chuàng)建的實(shí)例,是使用和Constructor對(duì)象同一個(gè)ClassLoader來創(chuàng)建的,換句話說,在同一個(gè)進(jìn)程中,同一個(gè)自定義View對(duì)象,是無法用不同ClassLoader加載的,如果想解決這個(gè)問題,就不要讓系統(tǒng)使用createView()接口創(chuàng)建View,做法就是自定義Factory或Factory2來自行創(chuàng)建View。
繼續(xù)往下看,如果緩存里沒有,則創(chuàng)建View的Class對(duì)象clazz,并緩存到sConstructorMap中,
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); } } constructor = clazz.getConstructor(mConstructorSignature); sConstructorMap.put(name, constructor); }
然后就是newInstance了,至此這個(gè)View便從xml中變成了java對(duì)象,我們繼續(xù)返回到inflate函數(shù)中,看看這個(gè)View返回之后做了什么,
...... // Temp is the root view that was found in the xml View temp; if (TAG_1995.equals(name)) { temp = new BlinkLayout(mContext, attrs); } else { temp = createViewFromTag(root, name, attrs); } ViewGroup.LayoutParams params = null; if (root != null) { // Create layout params that match root, if supplied params = root.generateLayoutParams(attrs); if (!attachToRoot) { // Set the layout params for temp if we are not // attaching. (If we are, we use addView, below) temp.setLayoutParams(params); } } // Inflate all children under temp rInflate(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.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; } ...... return result;
從createViewFromTag返回后,會(huì)調(diào)用個(gè)rInflate(),其中parent參數(shù)就是剛才創(chuàng)建出的View,應(yīng)該能猜到里面做了什么,
void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); int type; 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)) { parseRequestFocus(parser, parent); } else if (TAG_INCLUDE.equals(name)) { if (parser.getDepth() == 0) { throw new InflateException("<include /> cannot be the root element"); } parseInclude(parser, parent, attrs); } else if (TAG_MERGE.equals(name)) { throw new InflateException("<merge /> must be the root element"); } else if (TAG_1995.equals(name)) { final View view = new BlinkLayout(mContext, attrs); final ViewGroup viewGroup = (ViewGroup) parent; final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs); rInflate(parser, view, attrs, true); viewGroup.addView(view, params); } else { final View view = createViewFromTag(parent, name, attrs); final ViewGroup viewGroup = (ViewGroup) parent; final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs); rInflate(parser, view, attrs, true); viewGroup.addView(view, params); } } if (finishInflate) parent.onFinishInflate(); }
沒錯(cuò),就是遞歸的使用createViewFromTag()創(chuàng)建子View,并通過ViewGroup.addView添加到parent view中。
之后,這個(gè)View樹上的所有View都創(chuàng)建完畢。然后會(huì)根據(jù)inflate()的參數(shù)(root和attachToRoot)判斷是否將新創(chuàng)建的View添加到root view中,
if (root != null && attachToRoot) { root.addView(temp, params); }
然后,inflate()就將View返回了。
以上內(nèi)容是小編給大家介紹的android從xml加載到view對(duì)象過程解析,希望對(duì)大家有所幫助!
相關(guān)文章
Android利用CountDownTimer實(shí)現(xiàn)倒計(jì)時(shí)功能 Android實(shí)現(xiàn)停留5s跳轉(zhuǎn)到登錄頁面
這篇文章主要為大家詳細(xì)介紹了Android利用CountDownTimer實(shí)現(xiàn)倒計(jì)時(shí)功能,Android實(shí)現(xiàn)停留5s跳轉(zhuǎn)到登錄頁面,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07Android實(shí)現(xiàn)3秒鐘自動(dòng)關(guān)閉界面
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)3秒鐘自動(dòng)關(guān)閉界面,以支付成功為例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02android 開發(fā)教程之日歷項(xiàng)目實(shí)踐(二)
決定開始學(xué)習(xí) Android 平臺(tái)下的軟件開發(fā),以日歷作為實(shí)踐項(xiàng)目,進(jìn)行一周后,基本完成,有需要的朋友可以參考下2013-01-01Android圖片處理:識(shí)別圖像方向并顯示實(shí)例教程
在Android中使用ImageView顯示圖片的時(shí)候發(fā)現(xiàn)圖片顯示不正,方向偏了或者倒過來了,下面與大家分享下具體的解決方法,感性的朋友可以參考下2013-06-06Android BadgeView紅點(diǎn)更新信息提示示例代碼
本篇文章主要介紹了Android BadgeView紅點(diǎn)更新信息提示示例代碼,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-01-01Android仿微信朋友圈全文、收起功能的實(shí)例代碼
本篇文章主要介紹了Android仿微信朋友圈全文、收起功能的實(shí)例代碼,具有一定的參考價(jià)值,有興趣的可以了解一下2017-08-08淺談Android開發(fā)者2017年最值得關(guān)注的25個(gè)實(shí)用庫
本篇文章主要介紹了Android開發(fā)者2017年最值得關(guān)注的25個(gè)庫,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2017-09-09Kotlin Flow封裝類SharedFlow StateFlow LiveData使用
這篇文章主要為大家介紹了Kotlin Flow封裝類SharedFlow StateFlow LiveData使用對(duì)比,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08