全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

Android  LayoutInflater.inflate源码分析

LayoutInflater.inflate源码详解

LayoutInflater的inflate方法相信大家都不陌生,在Fragment的onCreateView中或者在BaseAdapter的getView方法中我们都会经常用这个方法来实例化出我们需要的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个参数的方法:

convertView = mInflater.inflate(R.layout.menu_item, null);

3个参数的方法(attachToRoot=false):

convertView = mInflater.inflate(R.layout.menu_item, parent, false);

3个参数的方法(attachToRoot=true):

convertView = mInflater.inflate(R.layout.menu_item, parent, true);

究竟我们应该用哪个方法进行实例化View,这3个方法又有什么区别呢?如果有同学对三个方法的区别还不是特别清楚,那么就和我一起从源码的角度来分析一下这个问题吧.

源码

inflate

我们先来看一下两个参数的inflate方法,源码如下:

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

从代码我们看出,其实两个参数的inflate方法根据父布局parent是否为null作为第三个参数来调用三个参数的inflate方法,三个参数的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解析方法是解析布局文件的.继续跟踪inflate方法源码:

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
  synchronized (mConstructorArgs) {
    // 获取上下文对象,即LayoutInflater.from传入的Context.
    final Context inflaterContext = mContext;
    // 根据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);
          }
          // 创建父类型的LayoutParams参数.
          params = root.generateLayoutParams(attrs);
          if (!attachToRoot) {
            // 如果实例化的View不需要添加到父布局上,则直接将根据父布局生成的params参数设置
            // 给它即可.
            temp.setLayoutParams(params);
          }
        }

        // 递归的创建当前布局的所有控件
        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;
  }
}

上述代码中的关键部分我已经加入了中文注释.从上述代码中我们还可以发现,我们传入的布局文件是通过createViewFromTag来实例化每一个子节点的.

createViewFromTag

函数源码如下:

/**
 * 方便调用5个参数的方法,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, 查询构造函数的缓存map中是否已经存在该View的构造函数.
  Constructor<? extends View> constructor = sConstructorMap.get(name);
  Class<? extends View> clazz = null;

  try {
    // 构造函数在缓存中未命中
    if (constructor == null) {
      // 通过类名去加载控件的字节码
      clazz = mContext.getClassLoader().loadClass(prefix != null ? (prefix + name) : name).asSubClass(View.class);
      // 如果有自定义的过滤器并且加载到字节码,则通过过滤器判断是否允许加载该View
      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 (mFilter != null) {
        // 过滤的map是否包含了此类名
        Boolean allowedState = mFilterMap.get(name);
        if (allowedState == null) {
          // 重新加载类的字节码
          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);
        }
      }
    }

    // 实例化类的参数数组(mConstructorArgs[0]为Context, [1]为View的属性)
    Object[] args = mConstructorArgs;
    args[1] = attrs;
    // 通过构造函数实例化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 {
    // ......
  }
}

总结

通过学习了inflate函数源码,我们再回过头去看BaseAdapter的那三种方法,我们可以得出的结论是:

第一种方法使用不够规范, 且会导致实例化View的LayoutParams属性失效.(ps: 即layout_width和layout_height等参数失效, 因为源码中这种情况的LayoutParams为null).

第二种是最正确,也是最标准的写法.

第三种由于attachToRoot为true,所以返回的View其实是父布局ListView,这显然不是我们想要实例化的View.因此,第三种写法是错误的.

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


# Android  # LayoutInflater.inflate源码  # LayoutInflater.inflate源码详解  # Android 老生常谈LayoutInflater的新认知  # Android中使用LayoutInflater要注意的一些坑  # Android布局加载之LayoutInflater示例详解  # Android LayoutInflater加载布局详解及实例代码  # Android LayoutInflater深入分析及应用  # Android开发中LayoutInflater用法详解  # 基于Android LayoutInflater的使用介绍  # Android用于加载xml的LayoutInflater源码超详细分析  # 加载  # 递归  # 值为  # 则将  # 第三种  # 的是  # 都不  # 还可以  # 不需要  # 和我  # 又有  # 这个问题  # 我们可以  # 对其  # 去看  # 希望能  # 如果没有  # 此类  # 三种  # 这种情况 


相关文章: 如何选择建站程序?包含哪些必备功能与类型?  建站之星客服服务时间及联系方式如何?  ,如何利用word制作宣传手册?  哈尔滨网站建设策划,哈尔滨电工证查询网站?  C++如何编写函数模板?(泛型编程入门)  如何通过FTP服务器快速搭建网站?  专业网站制作服务公司,有哪些网站可以免费发布招聘信息?  如何通过山东自助建站平台快速注册域名?  外贸公司网站制作哪家好,maersk船公司官网?  如何在IIS中新建站点并配置端口与IP地址?  建站主机服务器选型指南与性能优化方案解析  Dapper的Execute方法的返回值是什么意思 Dapper Execute返回值详解  建站之星后台管理系统如何操作?  建站主机选购指南:核心配置优化与品牌推荐方案  建站之星如何实现网站加密操作?  如何用PHP工具快速搭建高效网站?  惠州网站建设制作推广,惠州市华视达文化传媒有限公司怎么样?  如何彻底卸载建站之星软件?  制作无缝贴图网站有哪些,3dmax无缝贴图怎么调?  如何用IIS7快速搭建并优化网站站点?  如何快速建站并高效导出源代码?  完全自定义免费建站平台:主题模板在线生成一站式服务  ,购物网站怎么盈利呢?  建站主机选哪种环境更利于SEO优化?  黑客如何通过漏洞一步步攻陷网站服务器?  公司网站的制作公司,企业网站制作基本流程有哪些?  高端云建站费用究竟需要多少预算?  杭州银行网站设计制作流程,杭州银行怎么开通认证方式?  宝塔面板创建网站无法访问?如何快速排查修复?  武汉网站设计制作公司,武汉有哪些比较大的同城网站或论坛,就是里面都是武汉人的?  网站广告牌制作方法,街上的广告牌,横幅,用PS还是其他软件做的?  如何快速搭建个人网站并优化SEO?  制作旅游网站html,怎样注册旅游网站?  阿里云网站制作公司,阿里云快速搭建网站好用吗?  相亲简历制作网站推荐大全,新相亲大会主持人小萍萍资料?  怀化网站制作公司,怀化新生儿上户网上办理流程?  合肥做个网站多少钱,合肥本地有没有比较靠谱的交友平台?  网站微信制作软件,如何制作微信链接?  韩国代理服务器如何选?解析IP设置技巧与跨境访问优化指南  制作销售网站教学视频,销售网站有哪些?  c++怎么使用类型萃取type_traits_c++ 模板元编程类型判断【方法】  制作网站的基本流程,设计网站的软件是什么?  如何获取PHP WAP自助建站系统源码?  企业宣传片制作网站有哪些,传媒公司怎么找企业宣传片项目?  建站DNS解析失败?如何正确配置域名服务器?  网站网页制作专业公司,怎样制作自己的网页?  已有域名能否直接搭建网站?  济南网站建设制作公司,室内设计网站一般都有哪些功能?  三星网站视频制作教程下载,三星w23网页如何全屏?  齐河建站公司:营销型网站建设与SEO优化双核驱动策略 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。