需要导入什么,或者如何在活动之外的地方调用布局膨胀器?

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,这是一个限制吗?如果我想创建自定义对话框,我想为它膨胀视图,或者如果我想有吐司消息,自定义视图显示从一个服务,我只有来自服务的上下文,我没有任何活动,但我想显示自定义消息。

我需要在代码中不在活动类中的地方使用膨胀器。

我该怎么做呢?


当前回答

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

用这个代替吧!

其他回答

or

视图。膨胀(上下文,布局,父)

还是……

LayoutInflater inflater = LayoutInflater.from(context);

使用context对象,您可以从以下代码获得LayoutInflater

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

用这个代替吧!

LayoutInflater.from(context).inflate(R.layout.row_payment_gateway_item, null);