日本搞逼视频_黄色一级片免费在线观看_色99久久_性明星video另类hd_欧美77_综合在线视频

國(guó)內(nèi)最全I(xiàn)T社區(qū)平臺(tái) 聯(lián)系我們 | 收藏本站
阿里云優(yōu)惠2
您當(dāng)前位置:首頁(yè) > php開(kāi)源 > 綜合技術(shù) > 從源碼角度深入理解LayoutInflater

從源碼角度深入理解LayoutInflater

來(lái)源:程序員人生   發(fā)布時(shí)間:2016-02-28 10:21:42 閱讀次數(shù):2552次

關(guān)于LayoutInflater,在開(kāi)發(fā)中常常會(huì)遇到,特別是在使用ListView的時(shí)候,這個(gè)幾近是必不可少。今天我們就1起來(lái)探討LayoutInflater的工作原理。

1般情況下,有兩種方式取得1個(gè)LayoutInflater實(shí)例:

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

但是當(dāng)我們查看源碼的時(shí)候,卻發(fā)現(xiàn)這兩種實(shí)際上是1種,只不過(guò)第1種將第2種封裝了1下,我們看看from這個(gè)方法的源碼:

/** * 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對(duì)象以后,我們就能夠調(diào)用inflate來(lái)取得View對(duì)象了,inflate方法的源碼以下:

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

這里調(diào)用了1個(gè)inflate的1個(gè)重載方法,這個(gè)重載方法的最后1個(gè)參數(shù)和root有關(guān),如果我們的root為空,那末最后1個(gè)參數(shù)默許為false。我們看看這個(gè)重載方法:

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個(gè)XmlResourceParser 對(duì)象,最后inflate(parser, root, attachToRoot);又是調(diào)用1個(gè)重載方法:

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; } }

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

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

好啊,這里又調(diào)用了1個(gè)它的重載方法,那我們就看看這個(gè)重載方法,注意最后1個(gè)參數(shù)恒為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; } }

仔細(xì)分析1下這個(gè)重載方法,發(fā)現(xiàn)里邊的mFactory2和mFactory都為null,那末程序終究其實(shí)履行了這個(gè)方法里邊的這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; } }

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

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); } }

經(jīng)過(guò)了前兩個(gè)方法的相互扯皮,最后我們來(lái)到了第3個(gè)方法上,這是最后創(chuàng)建View的地方,代碼雖然很長(zhǎng),但是大家不用怕,這里的代碼我們主要分析下面這幾行,由于大部份不會(huì)被履行到。

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); } }

我把這個(gè)方法略微精簡(jiǎn)1下,可以看到,先是通過(guò)Java的反射機(jī)制拿到這個(gè)name所表示的布局對(duì)應(yīng)的那個(gè)Java類,然后是拿到構(gòu)造方法,最后通過(guò)構(gòu)造方法拿到1個(gè)View實(shí)例,邏輯還是比較清楚的。
好的,到這里,我們就已拿到根View了,現(xiàn)在我們?cè)倩氐缴厦嬲f(shuō)的那個(gè)inflate(…)方法中,在該方法中創(chuàng)建完temp這個(gè)View以后,接著就會(huì)履行到rInflateChildren(parser, temp, attrs, true);,里邊終究會(huì)履行到1個(gè)遞歸方法,這個(gè)方法是這樣的:

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(); } }

這個(gè)方法還不算長(zhǎng),進(jìn)入while循環(huán)以后,在if分支里會(huì)走到最后1個(gè)else里,這里還是先調(diào)用我們前文說(shuō)的那個(gè)createViewFromTag方法取得1個(gè)布局,然后遞歸,如果取得的這個(gè)View是個(gè)ViewGroup,那末會(huì)把它的子View添加到這個(gè)ViewGroup中,如果是普通View,那末接著循環(huán)就是了。做完這些以后,下面就和1開(kāi)始提到的root是不是為null有關(guān)了,如果root為null,那末attachToRoot這個(gè)參數(shù)為false,這個(gè)時(shí)候會(huì)履行:

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

然后我們解析過(guò)得到的View就會(huì)被返回,如果root不為null,那末attachToRoot這個(gè)參數(shù)默許為true,那末系統(tǒng)會(huì)履行

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

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

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


如果大家還有甚么問(wèn)題,歡迎留言討論

版權(quán)聲明:本文為博主原創(chuàng)文章,未經(jīng)博主允許不得轉(zhuǎn)載。若有毛病地方,還望批評(píng)指正,不勝感激。

生活不易,碼農(nóng)辛苦
如果您覺(jué)得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)
程序員人生
------分隔線----------------------------
分享到:
------分隔線----------------------------
關(guān)閉
程序員人生
主站蜘蛛池模板: 国产一区二区在线播放 | www国产亚洲精品久久麻豆 | 午夜精品一区二区三区在线 | 久久国产精品免费 | 欧美一区1区三区3区公司 | 日韩成人综合网 | 五月天激情婷婷 | 欧美视频精品 | 视频一区在线 | 青青草成人网 | 免费a在线观看 | 亚洲成人1区| 50岁女人一级毛片 | 国产精品三级在线 | 日韩中文字幕电影 | 国产理论 | 国产一区二区三区在线观看网站 | 国产精品久久久久久久久久久久久 | 亚洲欧美视频网站 | 久热久热| 精品国产污污免费网站精东 | 国产三级欧美三级日产三级99 | 精品在线视频观看 | 一级黄色毛片 | www.成人.com | 亚州国产 | 不卡三区 | 成人免费毛片aaaaaa片 | 日韩一级片毛片 | 亚洲免费a | 亚洲最大成人在线 | 久久xxx| 国产精品久久久久久久久久嫩草 | 国内精品久久久久久久影视简单 | 欧美一区二区三区在线视频 | 欧美日韩国产一区二区在线观看 | 久久久久久久av | 国产精一区 | 日韩大片免费观看 | 国产精品一区二区三区四区在线观看 | 亚洲天堂男人天堂 |