需要导入什么或者如何在 Activity 以外的地方调用布局充气器?
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 消息,我只有来自服务的上下文,我没有任何活动,该怎么办但我想显示自定义消息。
我需要在代码中不属于活动类的地方使用充气机。
我怎样才能做到这一点 ?
您可以使用此外部活动 - 您所需要的只是提供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 https://stackoverflow.com/a/18942760/157274关于如何获得LayoutInflater
实际上比我的更正确(尽管它仍然有效)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)