LayoutInflater与findViewById的区别?

  • 对于一个已经载入的界面,就可以使用findViewById()方法来获得其中的界面元素。
  • 对于一个没有被载入或者想要动态载入的界面,就需要使用LayoutInflater对象的inflate()方法来载入。
  • findViewById()是查找已被实例化为View对象的xml布局文件下的具体控件(如Button、TextView等),操作对象是一个ViewGroup或者是Activity,返回一个View对象。
  • LayoutInflater实例的inflate()方法是用来将res/layout/下的xml布局文件实例化,操作对象是XML文件,返回View对象。

LayoutInflater对象的获取方法

  1. 调用调用Activity对象的getLayoutInflater()

LayoutInflater inflater = getLayoutInflater();

  1. 通过Context的实例获取

LayoutInflater inflater = LayoutInflater.from(context);

  1. 还是通过Context的实例获取

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

上面获取LayoutInflater实例的方法实际上殊途同归,都是通过调用ContextgetSystemService方法去获取的。

先看第二种方法的实现的源码

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;
    }
复制代码

通过源码可以看出,第二种方法最终还是通过第三种方法实现的。

Activity 的 getLayoutInflater() 方法是调用 PhoneWindow 的getLayoutInflater()方法,源码如下:

public PhoneWindow(Context context) {
        super(context);
        mLayoutInflater = LayoutInflater.from(context);
    }

 public LayoutInflater getLayoutInflater() {
        return mLayoutInflater;
    }
复制代码

所以可以看出,上述三种方式最终本质是都是调用的Context实例的getSystemService()

inflate()方法

通过 sdk 的 api 文档,可以知道该方法有以下几种过载形式,返回值均是 View 对象:

  • public View inflate (int resource, ViewGroup root)

resource:View的layout的ID
root:如果为null,则将此View作为一个独立的View存在
如果!null, 那么该View会被直接addView进父View,然后将父View返回。

public View inflate (XmlPullParser parser, ViewGroup root)

parser:你需要解析xml的解析接口
root:如果为null,则将此View作为一个独立的View存在那么该View会被直接addView进父View,然后将父View返回。

  • public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot)

parser:你需要解析View的xml的解析接口。
如果root为Null,attachToRoot参数无效,而解析出的View作为一个独立的View存在。
如果 root不为Null,attachToRoot设为true,那么该View会被直接addView进父View,然后将父View返回。
如果root不为Null,attachToRoot为false,那么会给该View设置一个父View的约束(LayoutParams),然后将其返回。
当root不为null的话,attactToRoot的默认值是true。

public View inflate (int resource, ViewGroup root, boolean attachToRoot)

resource:View的layout的ID
如果root为Null,attachToRoot参数无效,而解析出的View作为一个独立的View存在。
如果 root不为Null,attachToRoot设为true,那么该View会被直接addView进父View,然后将父View返回。 如果root不为Null,attachToRoot为false,那么会给该View设置一个父View的约束(LayoutParams),然后将其返回。
当root不为null的话,attactToRoot的默认值是true。