在没有活动的地方调用 getLayoutInflater() [英] Call to getLayoutInflater() in places not in activity
问题描述
需要导入什么或如何在活动以外的地方调用 Layout inflater?
What does need to be imported or how can I call the Layout inflater in places other than activity?
public static void method(Context context){
//this doesn't work the getLayoutInflater method could not be found
LayoutInflater inflater = getLayoutInflater();
// this also doesn't work
LayoutInflater inflater = context.getLayoutInflater();
}
我只能在活动中调用 getLayoutInflater
,这是限制吗?如果我想创建自定义对话框并且想为其扩展视图怎么办,或者如果我想从服务中显示带有自定义视图的 Toast 消息怎么办,我只有来自服务的上下文我没有任何活动但我想显示自定义消息.
I am able to call getLayoutInflater
only in activity, is that an restriction? What if I want to create custom dialog and I want to inflate view for it, or what if I want to have Toast message with custom view that is shown from a service, I only have the context from the service I do not have any activity but I want to show custom message.
我需要在代码中不在活动类中的地方使用充气器.
I need the inflater in places in the code that isn't in the activity class.
我该怎么做?
推荐答案
你可以使用这个外部活动 - 你只需要提供一个Context
:
You can use this outside activities - all you need is to provide a Context
:
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
然后为了检索不同的小部件,您需要对布局进行膨胀:
Then to retrieve your different widgets, you inflate a layout:
View view = inflater.inflate( R.layout.myNewInflatedLayout, null );
Button myButton = (Button) view.findViewById( R.id.myButton );
<小时>
编辑截至 2014 年 7 月
Davide 关于如何获取 LayoutInflater
的 answer 实际上比我的更正确(其中仍然有效).
Davide's answer on how to get the LayoutInflater
is actually more correct than mine (which is still valid though).
这篇关于在没有活动的地方调用 getLayoutInflater()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!