Android 如何在给定上下文的情况下获得布局充气器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2212197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Get a Layout Inflater Given a Context?
提问by Edwin Lee
I am writing a custom implementation of a ListAdapter.
我正在编写 ListAdapter 的自定义实现。
In its constructor, I'm taking in a Context, a resource ID (i.e. R.id.xxx representing the layout file), and a list and a map (these contain the data).
在它的构造函数中,我接受了一个上下文、一个资源 ID(即表示布局文件的 R.id.xxx)以及一个列表和一个地图(这些包含数据)。
Now, the problem is that i will need a LayoutInflater to get the View object which is in the separate layout XML file.
现在,问题是我需要一个 LayoutInflater 来获取位于单独布局 XML 文件中的 View 对象。
How can I get hold of the LayoutInflater given only the Context?
仅给定上下文,我如何才能获得 LayoutInflater?
Now, why I think this is possible, is that this is quite similar to what is being passed in to the constructor of an ArrayAdapter (context, resource, textViewResourceId, data array), and I figure the ArrayAdapter also has to make use of a LayoutInflater given only a Context.
现在,为什么我认为这是可能的,是因为这与传递给 ArrayAdapter(上下文、资源、textViewResourceId、数据数组)的构造函数的内容非常相似,我认为 ArrayAdapter 还必须使用LayoutInflater 只给出了一个上下文。
But how can it be done?
但是怎么做呢?
回答by Dave Webb
You can use the static
from()
method from the LayoutInflater
class:
您可以使用类中的static
from()
方法LayoutInflater
:
LayoutInflater li = LayoutInflater.from(context);
回答by NguyenDat
You can also use this code to get LayoutInflater:
您还可以使用此代码来获取 LayoutInflater:
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)