在以下方面有什么真正的区别:
return context.getLayoutInflater().inflate(R.layout.my_layout, null);从指定的xml资源中膨胀新的视图层次结构。
和
return View.inflate(context, R.layout.my_layout, null);从XML资源中膨胀视图。这个方便的方法封装了LayoutInflater类,它为视图膨胀提供了一系列的选项。
发布于 2016-02-22 08:32:48
两者是一样的。第二个版本只是一个方便和简短的方法来完成这项任务。如果您看到View.inflate()方法的源代码,您会发现:
/**
* Inflate a view from an XML resource. This convenience method wraps the {@link
* LayoutInflater} class, which provides a full range of options for view inflation.
*
* @param context The Context object for your activity or application.
* @param resource The resource ID to inflate
* @param root A view group that will be the parent. Used to properly inflate the
* layout_* parameters.
* @see LayoutInflater
*/
public static View inflate(Context context, int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}它实际上在后端执行相同的工作,您提到的第一种方法就是这样做的。
发布于 2016-02-22 08:35:25
他们是一样的,做同样的事情。
在View.java类中
public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}LayoutInflater.from(context)返回LayoutInflator对象。这与调用getLayoutInflator()方法相同。
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;
}https://stackoverflow.com/questions/35548844
复制相似问题