几种获得LayoutInflater对象的方法以及区别

在代码中有以下三种获得LayoutInflater对象的方法,具体如下:

第一种方法:

LayoutInflater inflater = LayoutInflater.from(this); View layout = inflater.inflate(R.layout.main, null);

第二种方法:

LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.main, null);

第三种方法:

LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.main, null);

 

首先可查LayoutInflater.java源码可知:
/** * Obtains the LayoutInflater from the given 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; }

 LayoutInflater.from(context)的实质就是调用context.getSystemService(Context.LAYOUT_INFLATER_SERVICE),从而可知第一种方法和第三种方法本质是一样的

 

第二种方法其实就是调用的Window.getLayoutInflater()方法

/** * Quick access to the {@link LayoutInflater} instance that this Window * retrieved from its Context. * * @return LayoutInflater The shared LayoutInflater. */ public abstract LayoutInflater getLayoutInflater();

从其注释来看应该就相当于调用的是第一种方法

你可能感兴趣的:(service,layout,null,Access)