多多色-多人伦交性欧美在线观看-多人伦精品一区二区三区视频-多色视频-免费黄色视屏网站-免费黄色在线

國內最全IT社區平臺 聯系我們 | 收藏本站
阿里云優惠2
您當前位置:首頁 > php開源 > 綜合技術 > 從源碼角度深入理解LayoutInflater

從源碼角度深入理解LayoutInflater

來源:程序員人生   發布時間:2016-02-28 10:21:42 閱讀次數:2540次

關于LayoutInflater,在開發中常常會遇到,特別是在使用ListView的時候,這個幾近是必不可少。今天我們就1起來探討LayoutInflater的工作原理。

1般情況下,有兩種方式取得1個LayoutInflater實例:

LayoutInflater inflater1, inflater2; inflater1 = LayoutInflater.from(this); inflater2 = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

但是當我們查看源碼的時候,卻發現這兩種實際上是1種,只不過第1種將第2種封裝了1下,我們看看from這個方法的源碼:

/** * Obtains the LayoutInflater from the given context. */ public static LayoutInflater from(Context context) { LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (LayoutInflater == null) { throw new AssertionError("LayoutInflater not found."); } return LayoutInflater; }

取得LayoutInflater對象以后,我們就能夠調用inflate來取得View對象了,inflate方法的源碼以下:

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) { return inflate(resource, root, root != null); }

這里調用了1個inflate的1個重載方法,這個重載方法的最后1個參數和root有關,如果我們的root為空,那末最后1個參數默許為false。我們看看這個重載方法:

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) { final Resources res = getContext().getResources(); if (DEBUG) { Log.d(TAG, "INFLATING from resource: "" + res.getResourceName(resource) + "" (" + Integer.toHexString(resource) + ")"); } final XmlResourceParser parser = res.getLayout(resource); try { return inflate(parser, root, attachToRoot); } finally { parser.close(); } }

可以看出,先是拿到布局的xml資源,然后,取得1個XmlResourceParser 對象,最后inflate(parser, root, attachToRoot);又是調用1個重載方法:

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 (DEBUG) { System.out.println("**************************"); System.out.println("Creating root view: " + name); System.out.println("**************************"); } if (TAG_MERGE.equals(name)) { if (root == null || !attachToRoot) { throw new InflateException("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 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 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); } } if (DEBUG) { System.out.println("-----> start inflating children"); } // Inflate all children under temp against its context. rInflateChildren(parser, temp, attrs, true); if (DEBUG) { System.out.println("-----> done inflating children"); } // 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; } } } 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 { // Dont retain static reference on context. mConstructorArgs[0] = lastContext; mConstructorArgs[1] = null; } Trace.traceEnd(Trace.TRACE_TAG_VIEW); return result; } }

這個方法有點長,前面都是1些簡單的判斷,1般情況下(特殊情況大家可以按相應的分支走),我們的程序會履行到final View temp = createViewFromTag(root, name, inflaterContext, attrs);這行代碼,這里創建了1個名為temp的view,如果我們傳進來的根布局為null的話,那末這里拿到的就是1個根布局。我們看看這個方法的源代碼:

private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) { return createViewFromTag(parent, name, context, attrs, false); }

好啊,這里又調用了1個它的重載方法,那我們就看看這個重載方法,注意最后1個參數恒為false。

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)) { // Lets party like its 1995! return new BlinkLayout(context, attrs); } try { View view; 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) { view = mPrivateFactory.onCreateView(parent, name, context, attrs); } if (view == null) { final Object lastContext = mConstructorArgs[0]; mConstructorArgs[0] = context; try { if (-1 == name.indexOf(.)) { view = onCreateView(parent, name, attrs); } else { view = createView(name, null, attrs); } } finally { mConstructorArgs[0] = lastContext; } } return view; } catch (InflateException e) { throw e; } catch (ClassNotFoundException e) { final InflateException ie = new InflateException(attrs.getPositionDescription() + ": Error inflating class " + name); ie.initCause(e); throw ie; } catch (Exception e) { final InflateException ie = new InflateException(attrs.getPositionDescription() + ": Error inflating class " + name); ie.initCause(e); throw ie; } }

仔細分析1下這個重載方法,發現里邊的mFactory2和mFactory都為null,那末程序終究其實履行了這個方法里邊的這1段:

if (view == null) { final Object lastContext = mConstructorArgs[0]; mConstructorArgs[0] = context; try { if (-1 == name.indexOf(.)) { view = onCreateView(parent, name, attrs); } else { view = createView(name, null, attrs); } } finally { mConstructorArgs[0] = lastContext; } }

前面的判斷不用說,后面的判斷,如果name中包括.,說明我們用的不是普通的view,有多是自定義View等等,這1條大家可以自行去研究,如果name中不包括.,那末程序會履行view = onCreateView(parent, name, attrs);,那末我們就去看看這個方法:

protected View onCreateView(View parent, String name, AttributeSet attrs) throws ClassNotFoundException { return onCreateView(name, attrs); } 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 { Constructorextends View> clazz = null; try { Trace.traceBegin(Trace.TRACE_TAG_VIEW, name); if (constructor == null) { // Class not found in the cache, see if its 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); 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[] args = mConstructorArgs; args[1] = attrs; 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])); } return view; } catch (NoSuchMethodException e) { InflateException ie = new InflateException(attrs.getPositionDescription() + ": Error inflating class " + (prefix != null ? (prefix + name) : name)); ie.initCause(e); throw ie; } catch (ClassCastException e) { // If loaded class is not a View subclass InflateException ie = new InflateException(attrs.getPositionDescription() + ": Class is not a View " + (prefix != null ? (prefix + name) : name)); ie.initCause(e); throw ie; } catch (ClassNotFoundException e) { // If loadClass fails, we should propagate the exception. throw e; } catch (Exception e) { InflateException ie = new InflateException(attrs.getPositionDescription() + ": Error inflating class " + (clazz == null ? "" : clazz.getName())); ie.initCause(e); throw ie; } finally { Trace.traceEnd(Trace.TRACE_TAG_VIEW); } }

經過了前兩個方法的相互扯皮,最后我們來到了第3個方法上,這是最后創建View的地方,代碼雖然很長,但是大家不用怕,這里的代碼我們主要分析下面這幾行,由于大部份不會被履行到。

public final View createView(String name, String prefix, AttributeSet attrs) throws ClassNotFoundException, InflateException { ..... ..... if (constructor == null) { // Class not found in the cache, see if its real, and try to add it clazz = mContext.getClassLoader().loadClass( prefix != null ? (prefix + name) : name).asSubclass(View.class); ..... ..... constructor = clazz.getConstructor(mConstructorSignature); constructor.setAccessible(true); sConstructorMap.put(name, constructor); } Object[] args = mConstructorArgs; args[1] = attrs; 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])); } return view; }traceEnd(Trace.TRACE_TAG_VIEW); } }

我把這個方法略微精簡1下,可以看到,先是通過Java的反射機制拿到這個name所表示的布局對應的那個Java類,然后是拿到構造方法,最后通過構造方法拿到1個View實例,邏輯還是比較清楚的。
好的,到這里,我們就已拿到根View了,現在我們再回到上面說的那個inflate(…)方法中,在該方法中創建完temp這個View以后,接著就會履行到rInflateChildren(parser, temp, attrs, true);,里邊終究會履行到1個遞歸方法,這個方法是這樣的:

void rInflate(XmlPullParser parser, View parent, Context context, 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_TAG.equals(name)) { parseViewTag(parser, parent, attrs); } else if (TAG_INCLUDE.equals(name)) { if (parser.getDepth() == 0) { throw new InflateException("cannot be the root element"); } parseInclude(parser, context, parent, attrs); } else if (TAG_MERGE.equals(name)) { throw new InflateException("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); rInflateChildren(parser, view, attrs, true); viewGroup.addView(view, params); } } if (finishInflate) { parent.onFinishInflate(); } }

這個方法還不算長,進入while循環以后,在if分支里會走到最后1個else里,這里還是先調用我們前文說的那個createViewFromTag方法取得1個布局,然后遞歸,如果取得的這個View是個ViewGroup,那末會把它的子View添加到這個ViewGroup中,如果是普通View,那末接著循環就是了。做完這些以后,下面就和1開始提到的root是不是為null有關了,如果root為null,那末attachToRoot這個參數為false,這個時候會履行:

if (root == null || !attachToRoot) { result = temp; }

然后我們解析過得到的View就會被返回,如果root不為null,那末attachToRoot這個參數默許為true,那末系統會履行

if (root != null && attachToRoot) { root.addView(temp, params); }

也就是會把root套在我們解析得到的View以外,然后返回。

好了,到這里我們的LayoutInflater基本上就分析完了.


如果大家還有甚么問題,歡迎留言討論

版權聲明:本文為博主原創文章,未經博主允許不得轉載。若有毛病地方,還望批評指正,不勝感激。

生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈
程序員人生
------分隔線----------------------------
分享到:
------分隔線----------------------------
關閉
程序員人生
主站蜘蛛池模板: 国产色综合一区二区三区 | 久久久久久亚洲精品 | 一二三四视频中文字幕在线看 | 欧美一区二区三区在线观看 | 免费叼嘿视频 | 日韩一本二本 | 中文字幕一区二区三区乱码 | 欧美一区永久视频免费观看 | 一区二区三区影视 | 日韩一区二区视频在线观看 | 国产高清一区二区三区视频 | 欧洲天堂网 | 亚洲国产精品一区二区三区久久 | 最近中文字幕免费6 | 中文字幕国产视频 | 色综合亚洲精品激情狠狠 | 影视精品网站入口 | 精品久久中文网址 | 999精品久久久中文字幕蜜桃 | 白浆都出来了视频国产精品 | 日韩欧美视频一区二区在线观看 | 久久久毛片免费全部播放 | 日韩中文字幕精品免费一区 | 国产九色 | 久久这里只有精品9 | 性欧美video高清熟睡 | 叼嘿视频在线观看 | 伊人成伊人成综合网2222 | 国产成人久久精品二区三区 | 日韩一级片免费在线观看 | 色阁在线 | 欧美最猛性xxxxx免费 | 一区二区三区亚洲 | 视频一区亚洲 | 依人在线 | 久久久久久久久久久久久久久久久久久久 | 亚洲狠狠 | 久久久亚洲欧洲日产国码606 | 亚洲欧美一区二区三区不卡 | 亚洲精品国产v片在线观看 亚洲精品国产啊女成拍色拍 | 亚洲精品精品一区 |