Android LayoutInflate(一)

来源:互联网 发布:我要开淘宝网店怎么开 编辑:程序博客网 时间:2024/06/05 08:00

推卸责任和默默填坑,怎么选择?

LayoutInflater

项目中,我们通常通过LayoutInflater来找res/layout/下的xml布局文件,并且实例化。

怎么获取LayoutInflater

LayoutInflater 是一个抽象类,在文档中如下声明:
public abstract class LayoutInflater extends Object

`获得 LayoutInflater 实例的三种方式

//Activity调用getLayoutInflater() 1. LayoutInflater inflater = getLayoutInflater();2. LayoutInflater inflater = LayoutInflater.from(context);  3. LayoutInflater inflater =  (LayoutInflater)context.getSystemService                              (Context.LAYOUT_INFLATER_SERVICE);

其实最后还是通过第三种方式获取:

Activity 的 getLayoutInflater() 方法是调用 PhoneWindow 的getLayoutInflater()方法,看一下该源代码:

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

可以看出它其实是调用LayoutInflater.from(context)

LayoutInflater.from(context):

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;}

最后调用 context.getSystemService()。

0 0