如何获得给定上下文的布局充气机?


226

我正在编写ListAdapter的自定义实现。

在其构造函数中,我将获取一个Context,一个资源ID(即R.id.xxx代表布局文件)以及一个列表和一个映射(其中包含数据)。

现在,问题是我将需要一个LayoutInflater来获取位于单独的布局XML文件中的View对象。

仅给出上下文,如何才能获得LayoutInflater?

现在,为什么我认为这是可行的,是因为这与传递给ArrayAdapter的构造函数(上下文,资源,textViewResourceId,数据数组)非常相似,而且我认为ArrayAdapter也必须利用LayoutInflater仅提供了一个上下文。

但是怎么办呢?

Answers:


515

您可以使用类中static from()方法LayoutInflater

 LayoutInflater li = LayoutInflater.from(context);

11
谢谢!我试图找到Context.getSomething()。getAnotherThing()。getLayoutInflater()!
Edwin Lee,2010年

这是唯一对我有用的方法。到目前为止,我尝试过的所有其他方法都引发了异常。
num1

4
每次需要时都需要购买充气机,这是否昂贵?也就是说,您认为我们应该节省一个充气机成员吗?
2014年

顺便说一句,我认为我们应该使用LayoutInflater li =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE),因为最终LayoutInflater.from(context)在内部也做同样的事情。
Ankur Chaudhary 2015年

3
哪一个更好呢?是270票还是25以上的
DJphy 2015年

53

您还可以使用以下代码获取LayoutInflater:

LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)

40
LayoutInflater.from(Context ctx)和此getSustemService(...)之间有什么区别?
张宗平2012年

8
+1,一个很好的问题,在方法LayoutInflater.from(context)的实现中,还调用context.getSystemService()从系统管理器获取LayoutInflater服务提供者。因此,调用堆栈中可能会有少量差异。
NguyenDat 2012年

11
如果无法收回充气机,则LayoutInflater.from(context)也会引发错误:这里的代码:public static LayoutInflater from(Context context){LayoutInflater LayoutInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 如果(LayoutInflater == null){抛出新的AssertionError(“找不到LayoutInflater。”); } return LayoutInflater; }
Hiep
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.