Android LayoutInflater深入分析及应用

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<? 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
        //如果缓存中没有需要的构造器,那就通过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);
          }
        }
        //将使用过的构造器缓存
        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);
      //通过反射获取需要的实例对象
      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 ? (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构造器,如果没有,则加载对应的类,并缓存该构造器,
2.利用构造器反射构造对应的View
3.如果是ViewStub则复制一个LayoutInflater对象传递给它

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。