我們從Activity的setContentView()入手,開始源碼解析,
//Activity.setContentViewpublic void setContentView(int layoutResID) {getWindow().setContentView(layoutResID);initActionBar();}//PhoneWindow.setContentViewpublic 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 xmlView 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來(lái)控制View的創(chuàng)建過(guò)程。
如果沒(méi)有Factory或創(chuàng)建失敗,那么走默認(rèn)邏輯。
先判斷name中是否有'.'字符,如果沒(méi)有,則認(rèn)為使用android自己的View,此時(shí)會(huì)在name的前面加上包名"android.view.";如果有這個(gè)'.',則認(rèn)為使用的自定義View,這時(shí)無(wú)需添加任何前綴,認(rèn)為name已經(jīng)包含全包名了。
最終,使用這個(gè)全包名的name來(lái)創(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 itclazz = 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 constructorif (mFilter != null) {// Have we seen this name before?Boolean allowedState = mFilterMap.get(name);if (allowedState == null) {// New class -- remember whether it is allowedclazz = 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)的,并且通過(guò)Constructor創(chuàng)建的實(shí)例,是使用和Constructor對(duì)象同一個(gè)ClassLoader來(lái)創(chuàng)建的,換句話說(shuō),在同一個(gè)進(jìn)程中,同一個(gè)自定義View對(duì)象,是無(wú)法用不同ClassLoader加載的,如果想解決這個(gè)問(wèn)題,就不要讓系統(tǒng)使用createView()接口創(chuàng)建View,做法就是自定義Factory或Factory2來(lái)自行創(chuàng)建View。
繼續(xù)往下看,如果緩存里沒(méi)有,則創(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 itclazz = 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 xmlView 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 suppliedparams = 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 temprInflate(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();}沒(méi)錯(cuò),就是遞歸的使用createViewFromTag()創(chuàng)建子View,并通過(guò)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ì)象過(guò)程解析,希望對(duì)大家有所幫助!
 
  | 
新聞熱點(diǎn)
疑難解答
圖片精選