如何在给定上下文的情况下获取布局充气机?

253

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

在它的构造函数中,我传入了一个Context、一个资源ID(即代表布局文件的R.id.xxx)以及一个列表和一个映射(这些包含数据)。

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

如何在仅给定Context的情况下获取LayoutInflater呢?

我认为这是可能的原因是,这与ArrayAdapter的构造函数中传递的内容非常相似(context、resource、textViewResourceId、data array),我想ArrayAdapter也必须使用一个只给出Context的LayoutInflater。

但是,该如何完成呢?

2个回答

567
你可以使用 LayoutInflater 类中的 static from() 方法
 LayoutInflater li = LayoutInflater.from(context);

14
谢谢!我正在尝试查找Context.getSomething().getAnotherThing().getLayoutInflater()! - Edwin Lee
这是唯一对我有效的方法。到目前为止,我尝试过的其他所有方法都抛出了异常。 - num1
5
每次获取解压器是否昂贵?也就是说,您认为我们应该保存一个解压器实例吗? - AlikElzin-kilaka
1
顺便说一句,我认为我们应该使用LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE),因为最终LayoutInflater.from(context)内部执行的也是同样的操作。 - Ankur Chaudhary
3
哪个更好?拥有270票的还是拥有25+票的? - DJphy
1
最好的方法是使用LayoutInflater.from(context)。它实际上与下面的context.getSystemService做的一样,但由于Android可能会更改底层方法,因此我们应该使用父方法。 - box

56

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

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

44
LayoutInflater.from(Context ctx) 和 this.getSystemService(...) 有什么区别? - Teo Choong Ping
10
在实现方法 LayoutInflater.from(context) 中,还需要调用 context.getSystemService() 从系统管理器中获取 LayoutInflater 服务提供者。因此,在调用堆栈中可能会有一些细微的差别。+1,感谢好问题。 - NguyenDat
14
如果无法检索到Inflater,则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; } - Hiep

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接