首页 文章

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

提问于
浏览
158

需要导入什么或如何在活动以外的地方调用布局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 回答

  • 349

    您可以使用此外部活动 - 您只需要提供 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 );
    

    EDIT as of July 2014

    Davide关于如何获得 LayoutInflateranswer实际上比我的更正确(虽然它仍然有效) .

  • 9

    要么 ...

    LayoutInflater inflater = LayoutInflater.from(context);
    
  • 232

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

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

    要么

    View.inflate(context, layout, parent)

相关问题