国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 系統(tǒng) > Android > 正文

Android LayoutInflater深入分析及應(yīng)用

2019-12-12 03:50:22
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

LayoutInflater解析

前言:

在Android中,如果是初級(jí)玩家,很可能對(duì)LayoutInflater不太熟悉,或許只是在Fragment的onCreateView()中模式化的使用過(guò)而已。但如果稍微有些工作經(jīng)驗(yàn)的人就知道,這個(gè)類有多么重要,它是連接布局XMl和Java代碼的橋梁,我們常常疑惑,為什么Android支持在XML書(shū)寫(xiě)布局?

我們想到的必然是Android內(nèi)部幫我們解析xml文件,LayoutInflater就是幫我們做了這個(gè)工作。
首先LayoutInflater是一個(gè)系統(tǒng)服務(wù),這個(gè)我們可以從from方法看出來(lái)

 /**   * 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ì)象之后就會(huì)調(diào)用其inflate方法進(jìn)行加載布局,inflate是一個(gè)重載方法

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

可以看到,我們調(diào)用2個(gè)參數(shù)的方法時(shí)候其默認(rèn)是添加到父布局中的(父布局一般不為空)

public View inflate(int resource, 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();    }  }

這個(gè)方法中,其實(shí)是使用Resources將資源ID還原為XMlResoourceParser對(duì)象,然后調(diào)用inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)方法,解析布局的具體步驟都是在這個(gè)方法中實(shí)現(xiàn)

public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {    synchronized (mConstructorArgs) {      Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");      final AttributeSet attrs = Xml.asAttributeSet(parser);      Context lastContext = (Context)mConstructorArgs[0];      mConstructorArgs[0] = mContext;      View result = root;      try {        // Look for the root node.        //1.循環(huán)尋找根節(jié)點(diǎn),其實(shí)就是節(jié)點(diǎn)指針遍歷的過(guò)程        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!");        }          //2.得到節(jié)點(diǎn)的名字,用于判斷該節(jié)點(diǎn)        final String name = parser.getName();        if (DEBUG) {          System.out.println("**************************");          System.out.println("Creating root view: "              + name);          System.out.println("**************************");        }          //3.對(duì)節(jié)點(diǎn)名字進(jìn)行判斷,然后是merge就將其添加到父布局中(依據(jù)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, attrs, false, false);        } else {        //4.創(chuàng)建根據(jù)節(jié)點(diǎn)創(chuàng)建View          // Temp is the root view that was found in the xml          final View temp = createViewFromTag(root, name, attrs, false);          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            //5.根據(jù)attrs生成布局參數(shù)            params = root.generateLayoutParams(attrs);            if (!attachToRoot) {              // Set the layout params for temp if we are not              // attaching. (If we are, we use addView, below)              //6.如果View不添加到父布局中,那就給其本身設(shè)置布局參數(shù)              temp.setLayoutParams(params);            }          }          if (DEBUG) {            System.out.println("-----> start inflating children");          }          // Inflate all children under temp          // 7.將該節(jié)點(diǎn)下的子View全部加載          rInflate(parser, temp, attrs, true, 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.          //8.如果添加到父布局中,直接addView          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.          //9.如果不添加到父布局,那么將自己返回          if (root == null || !attachToRoot) {            result = temp;          }        }      } 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;      }      Trace.traceEnd(Trace.TRACE_TAG_VIEW);      return result;    }  }

重點(diǎn)的步驟我已經(jīng)加上注釋了,核心

1.找到根布局標(biāo)簽
2.創(chuàng)建根節(jié)點(diǎn)對(duì)應(yīng)的View
3.創(chuàng)建其子View

我們從這里面可以看出來(lái),子View的解析其實(shí)都是rInflate方法,如果xml中有根布局,那么就調(diào)用createViewFromTag創(chuàng)建布局中的根View。我們也可以明白merge的原來(lái),因?yàn)樗苯诱{(diào)用rInflate添加到父View中,看到rInflate(parser, root, attrs, false, false)和rInflate(parser, temp, attrs, true, true)第二個(gè)參數(shù)區(qū)別我們就明白了。

接下來(lái)我們看下rInflate如何創(chuàng)建多個(gè)布局

void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs,      boolean finishInflate, boolean inheritContext) throws XmlPullParserException,      IOException {    //獲取當(dāng)前解析器指針?biāo)诠?jié)點(diǎn)處于布局層次    final int depth = parser.getDepth();    int type;    //進(jìn)行樹(shù)的深度優(yōu)先遍歷(如果一個(gè)節(jié)點(diǎn)有子節(jié)點(diǎn)將會(huì)再次進(jìn)入rInflate,否則繼續(xù)循環(huán))    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();      //如果其中有request_focus標(biāo)簽,那就給這個(gè)節(jié)點(diǎn)View設(shè)置焦點(diǎn)      if (TAG_REQUEST_FOCUS.equals(name)) {        parseRequestFocus(parser, parent);      //如果其中有tag標(biāo)簽,那就給這個(gè)節(jié)點(diǎn)View設(shè)置tag(key,value)      } else if (TAG_TAG.equals(name)) {        parseViewTag(parser, parent, attrs);      } else if (TAG_INCLUDE.equals(name)) {      //如果其中是include標(biāo)簽,如果include標(biāo)簽        if (parser.getDepth() == 0) {          throw new InflateException("<include /> cannot be the root element");        }        parseInclude(parser, parent, attrs, inheritContext);      } else if (TAG_MERGE.equals(name)) {        throw new InflateException("<merge /> must be the root element");      } else {          //創(chuàng)建該節(jié)點(diǎn)代表的View并添加到父view中,此外遍歷子節(jié)點(diǎn)        final View view = createViewFromTag(parent, name, attrs, inheritContext);        final ViewGroup viewGroup = (ViewGroup) parent;        final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);        rInflate(parser, view, attrs, true, true);        viewGroup.addView(view, params);      }    }      //代表著一個(gè)節(jié)點(diǎn)含其子節(jié)點(diǎn)遍歷結(jié)束    if (finishInflate) parent.onFinishInflate();  }

從上面可以看到,所以創(chuàng)建View都將會(huì)交給createViewFromTag(View parent, String name, AttributeSet attrs, boolean inheritContext)中,我們可以看下該方法如何創(chuàng)建View

View createViewFromTag(View parent, String name, AttributeSet attrs, boolean inheritContext) {    if (name.equals("view")) {      name = attrs.getAttributeValue(null, "class");    }    Context viewContext;    if (parent != null && inheritContext) {      viewContext = parent.getContext();    } else {      viewContext = mContext;    }    // Apply a theme wrapper, if requested.    final TypedArray ta = viewContext.obtainStyledAttributes(attrs, ATTRS_THEME);    final int themeResId = ta.getResourceId(0, 0);    if (themeResId != 0) {      viewContext = new ContextThemeWrapper(viewContext, themeResId);    }    ta.recycle();    if (name.equals(TAG_1995)) {      // Let's party like it's 1995!      return new BlinkLayout(viewContext, attrs);    }    if (DEBUG) System.out.println("******** Creating view: " + name);    try {      View view;      if (mFactory2 != null) {        view = mFactory2.onCreateView(parent, name, viewContext, attrs);      } else if (mFactory != null) {        view = mFactory.onCreateView(name, viewContext, attrs);      } else {        view = null;      }      if (view == null && mPrivateFactory != null) {        view = mPrivateFactory.onCreateView(parent, name, viewContext, attrs);      }      if (view == null) {        final Object lastContext = mConstructorArgs[0];        mConstructorArgs[0] = viewContext;        try {          if (-1 == name.indexOf('.')) {            view = onCreateView(parent, name, attrs);          } else {            view = createView(name, null, attrs);          }        } finally {          mConstructorArgs[0] = lastContext;        }      }      if (DEBUG) System.out.println("Created view is: " + view);      return view;    } catch (InflateException e) {      throw e;    } catch (ClassNotFoundException e) {      InflateException ie = new InflateException(attrs.getPositionDescription()          + ": Error inflating class " + name);      ie.initCause(e);      throw ie;    } catch (Exception e) {      InflateException ie = new InflateException(attrs.getPositionDescription()          + ": Error inflating class " + name);      ie.initCause(e);      throw ie;    }  }

其實(shí)很簡(jiǎn)單,就是4個(gè)降級(jí)處理

if(factory2!=null){ factory2.onCreateView(); }else if(factory!=null){ factory.onCreateView(); }else if(mPrivateFactory!=null){ mPrivateFactory.onCreateView(); }else{ onCreateView() }

其他的onCreateView我們不去設(shè)置的話為null,我們看下自己的onCreateView(),其實(shí)這個(gè)方法會(huì)調(diào)用createView()

public final View createView(String name, String prefix, AttributeSet attrs)      throws ClassNotFoundException, InflateException {      //從構(gòu)造器Map(緩存)中獲取需要的構(gòu)造器    Constructor<? extends View> constructor = sConstructorMap.get(name);    Class<? extends View> clazz = null;    try {      Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);      if (constructor == null) {        // Class not found in the cache, see if it's real, and try to add it        //如果緩存中沒(méi)有需要的構(gòu)造器,那就通過(guò)ClassLoader加載需要的類        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);          }        }        //將使用過(guò)的構(gòu)造器緩存        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;      constructor.setAccessible(true);      //通過(guò)反射獲取需要的實(shí)例對(duì)象      final View view = constructor.newInstance(args);      if (view instanceof ViewStub) {        // Use the same context when inflating ViewStub later.        final ViewStub viewStub = (ViewStub) view;        //ViewStub將創(chuàng)建一個(gè)屬于自己的LayoutInflater,因?yàn)樗枰诓煌臅r(shí)機(jī)去inflate        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 ? "<unknown>" : clazz.getName()));      ie.initCause(e);      throw ie;    } finally {      Trace.traceEnd(Trace.TRACE_TAG_VIEW);    }  }

大體步驟就是,

1.從緩存中獲取特定View構(gòu)造器,如果沒(méi)有,則加載對(duì)應(yīng)的類,并緩存該構(gòu)造器,
2.利用構(gòu)造器反射構(gòu)造對(duì)應(yīng)的View
3.如果是ViewStub則復(fù)制一個(gè)LayoutInflater對(duì)象傳遞給它

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 抚宁县| 石棉县| 晴隆县| 曲水县| 岳阳市| 遵义县| 正镶白旗| 宜君县| 冷水江市| 资阳市| 大庆市| 德保县| 桑日县| 华池县| 阳山县| 涿鹿县| 眉山市| 句容市| 浮山县| 天柱县| 龙井市| 车险| 蚌埠市| 荔浦县| 平武县| 亚东县| 布拖县| 胶南市| 禹城市| 广饶县| 博野县| 辰溪县| 华安县| 大连市| 宁河县| 固安县| 康保县| 苗栗市| 开原市| 夏津县| 洪洞县|