需要导入什么或如何在活动以外的地方调用布局inflater?
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消息,我只有来自服务的上下文我没有任何活动该怎么办?但我想显示自定义消息 .
我需要在代码中不在activity类中的地方使用inflater .
我怎样才能做到这一点 ?
4 回答
您可以使用此外部活动 - 您只需要提供
Context
:然后,要检索不同的小部件,您需要扩展布局:
EDIT as of July 2014
Davide关于如何获得
LayoutInflater
的answer实际上比我的更正确(虽然它仍然有效) .要么 ...
使用上下文对象,您可以从以下代码获取LayoutInflater
要么
View.inflate(context, layout, parent)