91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

LayoutInflater怎么在Android 應用中使用

發布時間:2020-11-21 15:46:13 來源:億速云 閱讀:163 作者:Leah 欄目:移動開發

今天就跟大家聊聊有關LayoutInflater怎么在Android 應用中使用,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。

LayoutInflater解析

前言:

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

我們想到的必然是Android內部幫我們解析xml文件,LayoutInflater就是幫我們做了這個工作。
首先LayoutInflater是一個系統服務,這個我們可以從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方法進行加載布局,inflate是一個重載方法

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

可以看到,我們調用2個參數的方法時候其默認是添加到父布局中的(父布局一般不為空)

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

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

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.循環尋找根節點,其實就是節點指針遍歷的過程
        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.得到節點的名字,用于判斷該節點
        final String name = parser.getName();

        if (DEBUG) {
          System.out.println("**************************");
          System.out.println("Creating root view: "
              + name);
          System.out.println("**************************");
        }
          //3.對節點名字進行判斷,然后是merge就將其添加到父布局中(依據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.創建根據節點創建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.根據attrs生成布局參數
            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不添加到父布局中,那就給其本身設置布局參數
              temp.setLayoutParams(params);
            }
          }

          if (DEBUG) {
            System.out.println("-----> start inflating children");
          }
          // Inflate all children under temp
          // 7.將該節點下的子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;
    }
  }

重點的步驟我已經加上注釋了,核心

1.找到根布局標簽
2.創建根節點對應的View
3.創建其子View

我們從這里面可以看出來,子View的解析其實都是rInflate方法,如果xml中有根布局,那么就調用createViewFromTag創建布局中的根View。我們也可以明白merge的原來,因為它直接調用rInflate添加到父View中,看到rInflate(parser, root, attrs, false, false)和rInflate(parser, temp, attrs, true, true)第二個參數區別我們就明白了。

接下來我們看下rInflate如何創建多個布局

void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs,
      boolean finishInflate, boolean inheritContext) throws XmlPullParserException,
      IOException {
    //獲取當前解析器指針所在節點處于布局層次
    final int depth = parser.getDepth();
    int type;
    //進行樹的深度優先遍歷(如果一個節點有子節點將會再次進入rInflate,否則繼續循環)
    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標簽,那就給這個節點View設置焦點
      if (TAG_REQUEST_FOCUS.equals(name)) {
        parseRequestFocus(parser, parent);
      //如果其中有tag標簽,那就給這個節點View設置tag(key,value)
      } else if (TAG_TAG.equals(name)) {
        parseViewTag(parser, parent, attrs);
      } else if (TAG_INCLUDE.equals(name)) {
      //如果其中是include標簽,如果include標簽
        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 {
          //創建該節點代表的View并添加到父view中,此外遍歷子節點
        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);
      }
    }
      //代表著一個節點含其子節點遍歷結束
    if (finishInflate) parent.onFinishInflate();
  }

從上面可以看到,所以創建View都將會交給createViewFromTag(View parent, String name, AttributeSet attrs, boolean inheritContext)中,我們可以看下該方法如何創建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;
    }
  }

其實很簡單,就是4個降級處理

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

其他的onCreateView我們不去設置的話為null,我們看下自己的onCreateView(),其實這個方法會調用createView()

public final View createView(String name, String prefix, AttributeSet attrs)
      throws ClassNotFoundException, InflateException {
      //從構造器Map(緩存)中獲取需要的構造器
    Constructor<&#63; extends View> constructor = sConstructorMap.get(name);
    Class<&#63; 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
        //如果緩存中沒有需要的構造器,那就通過ClassLoader加載需要的類
        clazz = mContext.getClassLoader().loadClass(
            prefix != null &#63; (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 constructor
        if (mFilter != null) {
          // Have we seen this name before&#63;
          Boolean allowedState = mFilterMap.get(name);
          if (allowedState == null) {
            // New class -- remember whether it is allowed
            clazz = mContext.getClassLoader().loadClass(
                prefix != null &#63; (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);
      //通過反射獲取需要的實例對象
      final View view = constructor.newInstance(args);
      if (view instanceof ViewStub) {
        // Use the same context when inflating ViewStub later.
        final ViewStub viewStub = (ViewStub) view;
        //ViewStub將創建一個屬于自己的LayoutInflater,因為它需要在不同的時機去inflate
        viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
      }
      return view;

    } catch (NoSuchMethodException e) {
      InflateException ie = new InflateException(attrs.getPositionDescription()
          + ": Error inflating class "
          + (prefix != null &#63; (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 &#63; (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 &#63; "<unknown>" : clazz.getName()));
      ie.initCause(e);
      throw ie;
    } finally {
      Trace.traceEnd(Trace.TRACE_TAG_VIEW);
    }
  }

大體步驟就是,

1.從緩存中獲取特定View構造器,如果沒有,則加載對應的類,并緩存該構造器,
2.利用構造器反射構造對應的View
3.如果是ViewStub則復制一個LayoutInflater對象傳遞給它

看完上述內容,你們對LayoutInflater怎么在Android 應用中使用有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

永德县| 平顺县| 吐鲁番市| 黑水县| 汉沽区| 平泉县| 门源| 静安区| 临邑县| 全南县| 北安市| 深州市| 北海市| 黎城县| 宜宾县| 辉南县| 临桂县| 隆德县| 瑞昌市| 万山特区| 太和县| 金阳县| 怀仁县| 怀远县| 荣昌县| 南充市| 曲松县| 泸西县| 灌阳县| 封丘县| 永修县| 黄山市| 土默特左旗| 莱州市| 莆田市| 敖汉旗| 中卫市| 齐河县| 洪泽县| 互助| 伊吾县|