Android 中 LayoutInflater 的使用

一、LayoutInflater 的作用

我们一般使用 LayoutInflater 做一件事:View inflate(int resource, ViewGroup root); 

inflate() 的作用类似于 findViewById(); 不同的是 findViewById 用于查找某一具体 XML 下的具体的 widget 控件(如 TextView,Button 等待)而 inflate 则用于查找 /res/layout/文件夹下的 XML 布局文件并实例化,与 setContentView() 也有不同。

二、如何获取 LayoutInflater 对象

  1. 通过 LayoutInflater 的静态方法 from()
    LayoutInflater inflater = LayoutInflater.from(this);
    View view=inflater.inflate(R.layout.ID, null);
  2. 通过服务获取
    LayoutInflater inflater = (LayoutInflater)context.getSystemService
    (Context.LAYOUT_INFLATER_SERVICE);
  3. 通过 Activity 的 getLayoutInflater() 方法
    LayoutInflater inflater = getLayoutInflater();

三、inflate 和 findById 的注意细节

虽然 Layout 也是 View 的子类,但在 Android 中如果想将 XML 中的 Layout 转换为 View 放入 .java 代码中操作,只能通过 Inflater,而不能通过 findViewById()。 

四、inflate 和 setContentView 的区别

  • inflate 常用的方法形式为 View inflate(int resource, ViewGroup root); resource 为布局文件在 R.java 文件中的 ID 常量,这这个值必须指定,root 为可以为空,为空时只是实例化当前布局文件,当 root 不为空时,自动将当前实例化的布局文件对象加为 root 的 child。
  • setContentView 的方法形式为 void setContentView(int layoutResID) layoutResId 同 inflater 方法的 resource 参数。

两者的区别在于 setContentView 一旦调用,则立即显示 UI,inflate只会把Layout形成一个以view类实现成的对象,有需要时再用setContentView(view)显示出来。一般在activity 中通过 setContentView 将界面显示出来,但是如果在非 activity 对控件布局设置操作,这需 LayoutInflater 动态加载。

原文地址:https://www.cnblogs.com/tannerBG/p/4341929.html