Android LayoutInflater.inflate源碼分析
LayoutInflater.inflate源碼詳解
LayoutInflater的inflate方法相信大家都不陌生,在Fragment的onCreateView中或者在BaseAdapter的getView方法中我們都會經(jīng)常用這個方法來實例化出我們需要的View.
假設我們有一個需要實例化的布局文件menu_item.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/id_menu_title_tv" android:layout_width="match_parent" android:layout_height="300dp" android:gravity="center_vertical" android:textColor="@android:color/black" android:textSize="16sp" android:text="@string/menu_item"/> </LinearLayout>
我們想在BaseAdapter的getView()方法中對其進行實例化,其實例化的方法有三種,分別是:
2個參數(shù)的方法:
convertView = mInflater.inflate(R.layout.menu_item, null);
3個參數(shù)的方法(attachToRoot=false):
convertView = mInflater.inflate(R.layout.menu_item, parent, false);
3個參數(shù)的方法(attachToRoot=true):
convertView = mInflater.inflate(R.layout.menu_item, parent, true);
究竟我們應該用哪個方法進行實例化View,這3個方法又有什么區(qū)別呢?如果有同學對三個方法的區(qū)別還不是特別清楚,那么就和我一起從源碼的角度來分析一下這個問題吧.
源碼
inflate
我們先來看一下兩個參數(shù)的inflate方法,源碼如下:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) { return inflate(resource, root, root != null); }
從代碼我們看出,其實兩個參數(shù)的inflate方法根據(jù)父布局parent是否為null作為第三個參數(shù)來調(diào)用三個參數(shù)的inflate方法,三個參數(shù)的inflate方法源碼如下:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) { // 獲取當前應用的資源集合 final Resources res = getContext().getResources(); // 獲取指定資源的xml解析器 final XmlResourceParser parser = res.getLayout(resource); try { return inflate(parser, root, attachToRoot); } finally { // 返回View之前關閉parser資源 parser.close(); } }
這里需要解釋一下,我們傳入的資源布局id是無法直接實例化的,需要借助XmlResourceParser.
而XmlResourceParser是借助Android的pull解析方法是解析布局文件的.繼續(xù)跟蹤inflate方法源碼:
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) { synchronized (mConstructorArgs) { // 獲取上下文對象,即LayoutInflater.from傳入的Context. final Context inflaterContext = mContext; // 根據(jù)parser構建XmlPullAttributes. final AttributeSet attrs = Xml.asAttributeSet(parser); // 保存之前的Context對象. Context lastContext = (Context) mConstructorArgs[0]; // 賦值為傳入的Context對象. mConstructorArgs[0] = inflaterContext; // 注意,默認返回的是父布局root. View result = root; try { // 查找xml的開始標簽. int type; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { // Empty } // 如果沒有找到有效的開始標簽,則拋出InflateException異常. if (type != XmlPullParser.START_TAG) { throw new InflateException(parser.getPositionDescription() + ": No start tag found!"); } // 獲取控件名稱. final String name = parser.getName(); // 特殊處理merge標簽 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, inflaterContext, attrs, false); } else { // 實例化我們傳入的資源布局的view final View temp = createViewFromTag(root, name, inflaterContext, attrs); ViewGroup.LayoutParams params = null; // 如果傳入的parent不為空. if (root != null) { if (DEBUG) { System.out.println("Creating params from root: " + root); } // 創(chuàng)建父類型的LayoutParams參數(shù). params = root.generateLayoutParams(attrs); if (!attachToRoot) { // 如果實例化的View不需要添加到父布局上,則直接將根據(jù)父布局生成的params參數(shù)設置 // 給它即可. temp.setLayoutParams(params); } } // 遞歸的創(chuàng)建當前布局的所有控件 rInflateChildren(parser, temp, attrs, true); // 如果傳入的父布局不為null,且attachToRoot為true,則將實例化的View加入到父布局root中 if (root != null && attachToRoot) { root.addView(temp, params); } // 如果父布局為null或者attachToRoot為false,則將返回值設置成我們實例化的View 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 { // Don't retain static reference on context. mConstructorArgs[0] = lastContext; mConstructorArgs[1] = null; } Trace.traceEnd(Trace.TRACE_TAG_VIEW); return result; } }
上述代碼中的關鍵部分我已經(jīng)加入了中文注釋.從上述代碼中我們還可以發(fā)現(xiàn),我們傳入的布局文件是通過createViewFromTag來實例化每一個子節(jié)點的.
createViewFromTag
函數(shù)源碼如下:
/** * 方便調(diào)用5個參數(shù)的方法,ignoreThemeAttr的值為false. */ private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) { return createViewFromTag(parent, name, context, attrs, 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(); } // 特殊處理“1995”這個標簽(ps: 平時我們寫xml布局文件時基本沒有使用過). if (name.equals(TAG_1995)) { // Let's party like it's 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; } }
在createViewFromTag方法中,最終是通過createView方法利用反射來實例化view控件的.
createView
public final View createView(String name, String prefix, AttributeSet attrs) throws ClassNotFoundException, InflateException { // 以View的name為key, 查詢構造函數(shù)的緩存map中是否已經(jīng)存在該View的構造函數(shù). Constructor<? extends View> constructor = sConstructorMap.get(name); Class<? extends View> clazz = null; try { // 構造函數(shù)在緩存中未命中 if (constructor == null) { // 通過類名去加載控件的字節(jié)碼 clazz = mContext.getClassLoader().loadClass(prefix != null ? (prefix + name) : name).asSubClass(View.class); // 如果有自定義的過濾器并且加載到字節(jié)碼,則通過過濾器判斷是否允許加載該View if (mFilter != null && clazz != null) { boolean allowed = mFilter.onLoadClass(clazz); if (!allowed) { failNotAllowed(name, prefix, attrs); } } // 得到構造函數(shù) constructor = clazz.getConstructor(mConstructorSignature); constructor.setAccessible(true); // 緩存構造函數(shù) sConstructorMap.put(name, constructor); } else { if (mFilter != null) { // 過濾的map是否包含了此類名 Boolean allowedState = mFilterMap.get(name); if (allowedState == null) { // 重新加載類的字節(jié)碼 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); } } } // 實例化類的參數(shù)數(shù)組(mConstructorArgs[0]為Context, [1]為View的屬性) Object[] args = mConstructorArgs; args[1] = attrs; // 通過構造函數(shù)實例化View final View view = constructor.newInstance(args); if (View instanceof ViewStub) { final ViewStub viewStub = (ViewStub) view; viewStub.setLayoutInflater(cloneInContext((Context)args[0])) } return view; } catch (NoSunchMethodException e) { // ...... } catch (ClassNotFoundException e) { // ...... } catch (Exception e) { // ...... } finally { // ...... } }
總結(jié)
通過學習了inflate函數(shù)源碼,我們再回過頭去看BaseAdapter的那三種方法,我們可以得出的結(jié)論是:
第一種方法使用不夠規(guī)范, 且會導致實例化View的LayoutParams屬性失效.(ps: 即layout_width和layout_height等參數(shù)失效, 因為源碼中這種情況的LayoutParams為null).
第二種是最正確,也是最標準的寫法.
第三種由于attachToRoot為true,所以返回的View其實是父布局ListView,這顯然不是我們想要實例化的View.因此,第三種寫法是錯誤的.
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
Android實現(xiàn)Gesture手勢識別用法分析
這篇文章主要介紹了Android實現(xiàn)Gesture手勢識別用法,結(jié)合實例形式較為詳細的分析了Android基于Gesture實現(xiàn)手勢識別的原理與具體實現(xiàn)技巧,需要的朋友可以參考下2016-09-09Android?Spinner和GridView組件的使用示例
Spinner其實是一個列表選擇框,不過Android的列表選擇框并不需要顯示下拉列表,而是相當于彈出一個菜單供用戶選擇,GridView是一個在二維可滾動的網(wǎng)格中展示內(nèi)容的控件。網(wǎng)格中的內(nèi)容通過使用adapter自動插入到布局中2022-03-03Android自定義View模仿即刻點贊數(shù)字切換效果實例
有一個項目是仿即刻的點贊,這篇文章主要給大家介紹了關于Android自定義View模仿即刻點贊數(shù)字切換效果的相關資料,文中通過示例代碼介紹 的非常詳細,需要的朋友可以參考下2022-12-12詳解Android業(yè)務組件化之URL Schema使用
這篇文章主要為大家詳細介紹了Android業(yè)務組件化之URL Schema使用,感興趣的小伙伴們可以參考一下2016-09-09詳解Flutter WebView與JS互相調(diào)用簡易指南
這篇文章主要介紹了詳解Flutter WebView與JS互相調(diào)用簡易指南,分為JS調(diào)用Flutter和Flutter調(diào)用JS,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-04-04