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

Luk*_*kap 176 service android toast android-context layout-inflater

需要导入什么或如何在活动以外的地方调用布局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();
}
Run Code Online (Sandbox Code Playgroud)

getLayoutInflater只能在活动中打电话,这是限制吗?如果我想创建自定义对话框并且我想为它充气视图,或者如果我想要从服务中显示自定义视图的Toast消息,我只有来自服务的上下文我没有任何活动该怎么办?但我想显示自定义消息.

我需要在代码中不在activity类中的地方使用inflater.

我怎样才能做到这一点 ?

kas*_*rch 380

您可以使用此外部活动 - 您只需提供Context:

LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
Run Code Online (Sandbox Code Playgroud)

然后,要检索不同的小部件,您需要对布局进行扩充:

View view = inflater.inflate( R.layout.myNewInflatedLayout, null );
Button myButton = (Button) view.findViewById( R.id.myButton );
Run Code Online (Sandbox Code Playgroud)

编辑截至2014年7月

Davide 关于如何获得它的答案LayoutInflater实际上比我的更正确(尽管仍然有效).


Dav*_*ide 246

要么 ...

LayoutInflater inflater = LayoutInflater.from(context);
Run Code Online (Sandbox Code Playgroud)

  • 如此简短,充满热情 (35认同)
  • 很晚,但实际上是一个更好的答案,因为from函数也检查断言你实际上得到了一个inflater,否则抛出一个错误 - 这将更容易处理代码中某处的空指针excpetion.http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/view/LayoutInflater.java#LayoutInflater.from%28android.content.Context %29 (5认同)

Pra*_*dar 10

要么

View.inflate(context, layout, parent)


anu*_*har 9

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

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Run Code Online (Sandbox Code Playgroud)