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

标签 android service android-context toast layout-inflater

需要导入什么或者如何在activity以外的地方调用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();
}

我只能在 Activity 中调用 getLayoutInflater,这是限制吗?如果我想创建自定义对话框并且我想为它膨胀 View ,或者如果我想从服务中显示带有自定义 View 的 Toast 消息怎么办,我只有来自服务的上下文我没有任何 Activity 但我想显示自定义消息。

我需要在代码中不在 Activity 类中的地方使用充气器。

我该怎么做?

最佳答案

你可以使用这个外部 Activity ——你只需要提供一个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 月起

大卫的 answer关于如何获得 LayoutInflater 实际上比我的更正确(尽管它仍然有效)。

关于android - 在不活动的地方调用 getLayoutInflater(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7803771/

相关文章:

android - 当 Activity 被销毁时,回收者 View 会发生什么?

android - 持有应用程序上下文实例是一种不好的做法吗?

java - 如何在方向改变时停止整个 Activity 娱乐

java - 安卓 N : Platform Migration toward OpenJDK 8

java - 检查 OnTextChanged 内的空 EditText

php - 如何将程序安装为启动时自动启动的服务?

java - 通过 ksoap2 从 Android 调用 Java Web 服务

.net - 您如何保护和计量您与业务合作伙伴共享的 Web 服务?

Material 设计中的Android EditText View float 提示

android - Helper 文件中用于 Intent 和 Activity 导航的 AtomicReferences