【问题标题】:Android : What is the difference between View.inflate and getLayoutInflater().inflate?Android:View.inflate 和 getLayoutInflater().inflate 有什么区别?
【发布时间】:2016-02-22 08:22:20
【问题描述】:
两者之间的真正区别是什么:
return context.getLayoutInflater().inflate(R.layout.my_layout, null);
从指定的 xml 资源扩充新的视图层次结构。
和
return View.inflate(context, R.layout.my_layout, null);
从 XML 资源扩充视图。这个方便的方法包装了 LayoutInflater 类,它为视图膨胀提供了全方位的选项。
【问题讨论】:
标签:
android
layout
layout-inflater
【解决方案1】:
两者都是一样的。第二个版本只是完成任务的一种方便而简短的方法。如果你看到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);
}
您提到的第一种方法实际上在后端执行相同的工作。
【解决方案2】:
他们是一样的,做同样的事情
在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;
}