天天看点

【android】LayoutInflater 的 inflater 方法浅析

目录

  • 环境
  • 导读
  • 调用方法
  • 调用分析

环境

  • 操作系统:win7-64bit 旗舰版
  • android 版本:android-23

导读

大家使用的 LayoutInflater 的 inflater 方法的频率并不低,但可能对其中一些参数了解的不是很具体,本篇将为大家进行介绍分析。

调用方法

  • 获取 inflater 实例:
// this 表示 Activity 对象或其子类对象

// 方法1:
LayoutInflater inflater = this.getLayoutInflater();
// 方法2:
LayoutInflater inflater = (LayoutInflater)this.getSystemService( Context.LAYOUT_INFLATER_SERIVCE);
// 方法3:
LayoutInflater inflater = LayoutInflater.from(this);
           
  • 从 xml 中获取指定的布局:
// 常用方法1:
public View inflate(@LayoutRes int resource, ViewGroup root);
// 常用方法2:
public View inflate(@LayoutRes int resource, ViewGroup root, boolean attachToRoot);
           

调用分析

上面的两个 inflate 方法都最终会调用到:

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
           
  • 参数 boolean attachToRoot:
    • 作用:是否将从 xml 中获取到的布局通过 addView 的方式添加到 ViewGroup root 中;
      • 是:
      • 否:获取到的布局将匹配至 root 的 LayoutParams;
  • 参数 ViewGroup root:可以用来作为从 xml 中获取到的布局 View 的容器;
  • 返回值 View:返回内容与 参数 boolean attachToRoot 有关;
    • 若 attachToRoot 为 true:返回的是 ViewGroup root;
    • 若 attachToRoot 为 false:返回的是从 xml 中获取的布局;