欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android布局加载之LayoutInflater示例详解

程序员文章站 2022-07-21 15:20:30
前言 activity 在界面创建时需要将 xml 布局文件中的内容加载进来,正如我们在 listview 或者 recyclerview 中需要将 item 的布局加载...

前言

activity 在界面创建时需要将 xml 布局文件中的内容加载进来,正如我们在 listview 或者 recyclerview 中需要将 item 的布局加载进来一样,都是使用 layoutinflater 来进行操作的。

layoutinflater 实例的获取有多种方式,但最终是通过(layoutinflater)context.getsystemservice(context.layout_inflater_service)来得到的,也就是说加载布局的 layoutinflater 是来自于系统服务的。

由于 android 系统源码中关于 content 部分采用的是装饰模式,context 的具体功能都是由 contextimpl 来实现的。通过在 contextimpl 中找到getsystemservice的代码,一路跟进,得知最后返回的实例是phonelayoutinflater。

  registerservice(context.layout_inflater_service, layoutinflater.class,
    new cachedservicefetcher<layoutinflater>() {
   @override
   public layoutinflater createservice(contextimpl ctx) {
    return new phonelayoutinflater(ctx.getoutercontext());
   }});

layoutinflater 只是一个抽象类,而 phonelayoutinflater 才是具体的实现类。

inflate 方法加载 view

使用 layoutinflater 时常用方法就是inflate方法了,将一个布局文件 id 传入并最后解析成一个 view 。

layoutinflater 加载布局的 inflate 方法也有多种重载形式:

view inflate(@layoutres int resource, @nullable viewgroup root)
view inflate(@layoutres int resource, @nullable viewgroup root, boolean attachtoroot)

而这两者的差别就在于是否要将 resource 布局文件加载到 root布局中去。

不过有点需要注意的地方,若 root为 null,则在 xml 布局中为 resource设置的属性会失效,只是单纯的加载布局。

     // temp 是 xml 布局中的顶层 view
     final view temp = createviewfromtag(root, name, inflatercontext, attrs);
     viewgroup.layoutparams params = null;
     if (root != null) { // root 
      // root 不为 null 才会生成 layoutparams
      params = root.generatelayoutparams(attrs);
      if (!attachtoroot) {
       // 如果不添加到 root 中,则直接把布局参数设置给 temp
       temp.setlayoutparams(params);
      }
     }
     // 加载子 view 
     rinflatechildren(parser, temp, attrs, true);
     if (root != null && attachtoroot) {
      root.addview(temp, params);//添加到布局中,则布局参数用到 addview 中去
     }
     if (root == null || !attachtoroot) {
      result = temp;
     }

跟进createviewfromtag方法查看 view 是如何创建出来的。

   view view; // 最后要返回的 view
   if (mfactory2 != null) {
    view = mfactory2.oncreateview(parent, name, context, attrs); // 是否设置了 factory2 
   } else if (mfactory != null) {
    view = mfactory.oncreateview(name, context, attrs); // 是否设置了 factory
   } else {
    view = null;
   }
   if (view == null && mprivatefactory != null) { // 是否设置了 privatefactory
    view = mprivatefactory.oncreateview(parent, name, context, attrs);
   }
   if (view == null) { // 如果的 factory 都没有设置过,最后在生成 view
    final object lastcontext = mconstructorargs[0];
    mconstructorargs[0] = context;
    try {
     if (-1 == name.indexof('.')) { // 系统控件 
      view = oncreateview(parent, name, attrs);
     } else { // 非系统控件,自定义的 view 
      view = createview(name, null, attrs);
     }
    } finally {
     mconstructorargs[0] = lastcontext;
    }
   }

如果设置过 factory 接口,那么将由 factory 中的 oncreateview 方法来生成 view 。

关于 layoutinflater.factory 的作用,就是用来在加载布局时可以自行去创建 view,抢在系统创建 view 之前去创建。

关于 layoutinflater.factory 的使用场景,现在比较多的就是应用的换肤了。

若没有设置过 factory 接口,则是判断是否为自定义控件或者系统控件,不管是 oncreateview 方法还是 createview 方法,内部最终都是调用到了 createview 方法,通过它来生成 view 。

// 通过反射生成 view 的参数,分别是 context 和 attributeset 类
static final class<?>[] mconstructorsignature = new class[] {
   context.class, attributeset.class};
public final view createview(string name, string prefix, attributeset attrs)
   throws classnotfoundexception, inflateexception {
  constructor<? extends view> constructor = sconstructormap.get(name);
  class<? extends view> clazz = null;
  if (constructor == null) { // 从缓存中得到 view 的构造器,没有则调用 getconstructor
    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);
    constructor.setaccessible(true);
    sconstructormap.put(name, constructor);
   } else {
    // if we have a filter, apply it to cached constructor
    if (mfilter != null) { // 过滤,是否允许生成该 view
     // 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); // 不允许生成该 view
     }
    }
   }
  object[] args = mconstructorargs;
  args[1] = attrs;
  final view view = constructor.newinstance(args); // 通过反射生成 view
  return view;

在 createview 方法内部,首先从 view 的构造器缓存中查找是否有对应的缓存,若没有则生成构造器并且放到缓存中去,若有构造器则看能否通过过滤,是否允许该 view 生成。

最后都满足条件的则是通过 view 的构造器反射生成了 view 。

在生成 view 时采用 constructor.newinstance调用构造函数,而参数所需要的变量就是mconstructorsignature变量所定义的,分别是 context 和 attributeset。可以看到,在最后生成 view 时也传入了对应的参数。

采用 constructor.newinstance的形式反射生成 view ,是为了解耦,只需要有了类名,就可以加载出来。

由此可见,layoutinflater 加载布局仍然是需要传递 context的,不光是为了得到 layoutinflater ,在反射生成 view 时同样会用到。

深度遍历加载布局

如果需要加载的布局只有一个控件,那么 layoutinflater 返回那个 view 工作也就结束了。

若布局文件中有多个需要加载的 view ,则通过rinflatechildren方法继续加载顶层 view 下的 view ,最后通过rinflate方法来加载。

void rinflate(xmlpullparser parser, view parent, context context,
   attributeset attrs, boolean finishinflate) throws xmlpullparserexception, ioexception {
  final int depth = parser.getdepth();
  int type;
  // 若 while 条件不成立,则加载结束了
  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(); // 从 xmlpullparser 中得到 name 出来解析
   if (tag_request_focus.equals(name)) { // name 各种情况下的解析
    parserequestfocus(parser, parent);
   } else if (tag_tag.equals(name)) {
    parseviewtag(parser, parent, attrs);
   } else if (tag_include.equals(name)) {
    if (parser.getdepth() == 0) {
     throw new inflateexception("<include /> cannot be the root element");
    }
    parseinclude(parser, context, parent, attrs);
   } else if (tag_merge.equals(name)) {
    throw new inflateexception("<merge /> must be the root element");
   } else {
    final view view = createviewfromtag(parent, name, context, attrs);
    final viewgroup viewgroup = (viewgroup) parent;
    final viewgroup.layoutparams params = viewgroup.generatelayoutparams(attrs);
    rinflatechildren(parser, view, attrs, true); // 继续遍历
    viewgroup.addview(view, params); // 顶层 view 添加 子 view
   }
  }
  if (finishinflate) { // 遍历解析
   parent.onfinishinflate();
  }
 }

rinflate方法首先判断是否解析结束了,若没有,则从 xmlpullparser 中加载出下一个 view 进行处理,中间还会对不同的类型进行处理,比如tag_request_focus、tag_tag、tag_include、tag_merge等等。

最后仍然还是通过createviewfromtag来生成 view ,并以这个生成的 view 为父节点,开始深度遍历,继续调用rinflatechildren方法加载布局,并把这个 view 加入到它的父 view 中去。

至于为什么生成 view 的方法名字createviewfromtag从字面上来看是来自于 tag标签,想必是和 xmlpullparser解析布局生成的内容有关。

总结

以上就是这篇文章的全部内容了,希望本文的内容对各位android开发者们能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。