Android inflate解析

对于inflate,我相信大家都不陌生,它的作用是将一个layout.xml布局文件变为一个View对象。尤其在ListView、GridView的Adapter中,我们继承BaseAdapter时必须重写的几个方法中有一个getView()方法,在这个方法中基本都会出现,使用inflate方法去加载一个布局,作为ListView、GridView的每个Item的布局。这篇博客就来分析一下Android中inflate的过程。
摘要由CSDN通过智能技术生成

Android inflate解析

对于inflate,我相信大家都不陌生,它的作用是将一个layout.xml布局文件变为一个View对象。尤其在ListView、GridView、RecyclerView的Adapter还有组合自定义控件中,我们都会使用inflate()方法去加载一个布局,作为每个Item的布局。这篇博客就来分析一下Android中inflate是怎样将xml文件变为View的。

使用inflate,一般是调用两个类中的方法:

  • 使用View中的静态方法View.inflate()

      public static View inflate(Context context, @LayoutRes int resource, ViewGroup root)
    
  • 使用LayoutInflater中的inflate()方法,在LayoutInflater类中有几个重载方法

      public View inflate(@LayoutRes int resource, @Nullable ViewGroup root)
      public View inflate(XmlPullParser parser, @Nullable ViewGroup root)
      public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
      public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
    

inflate()方法内部调用过程

  • View#inflate()

      public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
          LayoutInflater factory = LayoutInflater.from(context);
          return factory.inflate(resource, root);
      }
    

    View.inflate() 调用了LayoutInflater中的inflate()方法,所以上面的两个类中的方法实际是一样的。下面看一下LayoutInflater的调用过程。

  • LayoutInflater#inflate()

      // 内部调用 inflate(resource, root, root != null)
      public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
          return inflate(resource, root, root != null);
      }
    
      // 内部调用 inflate(parser, root, attachToRoot)
      public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
          final Resources res = getContext().getResources();
          final XmlResourceParser parser = res.getLayout(resource);
          try {
              // 调用方法
              return inflate(parser, root, attachToRoot);
          } finally {
              parser.close();
          }
      }
    
      // 内部调用 inflate(resource, root, root != null)
      public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {
          return inflate(parser, root, root != null);
      }
    
      // 最终调用方法
      public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot){
          // 解析xml文件,返回View对象
      }
    

通过上面的调用过程可以看到,不管是View#inflate()方法还是LayoutInflater#inflate(),最终都是调用了同一个方法,那么我们就只需要接着看这个方法的解析过程就可以了。

获取 LayoutInflater 对象

在说 inflate() 的解析过程之前,我们先来看一下外部怎么调用LayoutInflater#in

  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值