需要导入什么或如何在活动以外的地方调用布局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。
我怎样才能做到这一点 ?
你可以使用这个户外活动 - 你需要的只是提供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月
Davide关于如何获得answer的LayoutInflater
实际上比我的更正确(尽管仍然有效)。
要么 ...
LayoutInflater inflater = LayoutInflater.from(context);
要么
View.inflate(context, layout, parent)
使用上下文对象,您可以从以下代码中获取LayoutInflater
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater.from(context).inflate(R.layout.row_payment_gateway_item, null);