202

需要导入什么或如何在活动以外的地方调用 Layout 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 消息怎么办,我只有来自服务的上下文我没有任何活动但我想显示自定义消息。

我需要在代码中不在活动类中的地方使用充气机。

我怎样才能做到这一点 ?

4

6 回答 6

426

您可以使用此外部活动 - 您只需提供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实际上比我的更正确(尽管它仍然有效)。

于 2011-10-18T07:31:07.263 回答
286

或者 ...

LayoutInflater inflater = LayoutInflater.from(context);
于 2013-09-22T10:21:40.917 回答
12

或者

View.inflate(context, layout, parent)

于 2014-06-10T21:50:46.270 回答
11

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

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
于 2011-10-18T07:31:31.103 回答
4
LayoutInflater.from(context).inflate(R.layout.row_payment_gateway_item, null);
于 2019-03-28T07:48:33.593 回答
3
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );

改用这个!

于 2019-09-07T10:48:34.620 回答