需要导入什么或者如何在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/