调用getLayoutInflater()在不在活动的地方

什么是需要导入的,或者如何在除了活动之外的地方调用布局充气器?

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(); } 

我只能在activity中调用getLayoutInflater ,这是一个限制吗? 如果我想创build自定义对话框,我想膨胀视图,或者如果我想要具有从服务显示的自定义视图的Toast消息,我只有从服务的上下文我没有任何活动但我想显示自定义消息。

我需要在不在activity类中的代码中的inflater。

我怎样才能做到这一点 ?

你可以使用这个外部活动 – 所有你需要的是提供一个Context

 LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE ); 

然后检索你的不同的小部件,你膨胀一个布局:

 View view = inflater.inflate( R.layout.myNewInflatedLayout, null ); Button myButton = (Button) view.findViewById( R.id.myButton ); 

编辑截至2014年7月

Davide关于如何获得LayoutInflater的回答实际上比我的更正确(尽pipe如此,仍然是有效的)。

要么 …

 LayoutInflater inflater = LayoutInflater.from(context); 

使用上下文对象,您可以从下面的代码中获取LayoutInflater

 LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

要么

View.inflate(context, layout, parent)