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

210
需要导入什么以及如何在非活动(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();
}

我只能在活动中调用getLayoutInflater,这是一种限制吗?如果我想创建自定义对话框并为其填充视图,或者如果我想要具有自定义视图的Toast消息,并且该消息是从服务显示的,我只有来自服务的上下文,没有任何活动,但我想显示自定义消息。

我需要在代码中不在活动类中的位置使用inflater。

我该如何做到这一点?

6个回答

439

您可以在活动之外使用此功能 - 您只需要提供一个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的回答关于如何获取LayoutInflater实际上比我的更正确(尽管我的仍然有效)。


太好了,但是现在findViewById不起作用了,你有什么想法吗?inflater.inflate(R.layout.some_layout, (ViewGroup) findViewById(R.id.parent)); - Lukap
nop,inflater.inflate()方法没有只带一个int参数的重载方法,但我猜下一个可能是null。 - Lukap
@kaspermoerch 你为什么说David的回答更正确? - Rohan Bhatia
1
@RohanBhatia Davide的答案不需要强制转换,而我的需要。如果getSystemService的调用由于某种(不太可能的)原因未返回LayoutInflater类型的对象,则我的代码将导致运行时异常。 - kaspermoerch
@TamásBolvári 不是的。这两种解决方案都是有效的。Davide的解决方案比我的简单,而且避免了将结果转换为LayoutInflater可能会失败的情况(尽管这不太可能)。 - kaspermoerch
显示剩余2条评论

297

Or ...

LayoutInflater inflater = LayoutInflater.from(context);

5
虽然有点晚了,但其实更好的答案是 from 函数还使用 assert 检查你是否确实得到了一个 inflater,否则会抛出错误 - 这将比代码中某个地方的空指针异常容易处理得多。 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 - Raanan
42
如此简洁,太多的充气器。 - Danyal Aytekin
@Davide 这个引用是不是意味着 kaspermoerch 的解决方案比你的更好?“它从未被直接使用。相反,使用 getLayoutInflater() 或 getSystemService(Class ) 来检索标准 LayoutInflater 实例,该实例已经连接到当前上下文并正确配置为您正在运行的设备。” https://developer.android.com/reference/android/view/LayoutInflater - Tamás Bolvári
@TamásBolvári 只是更加简单明了,实际上内部实现与 Kaspermoerch 所写的相同。 - Davide
太棒了,兄弟!感谢你在2022年。 - Osdward

12

or

View.inflate(context, layout, parent)


这没问题;然而,使用这种方法,我无法提供布尔值“attachToRoot”。 - DenisGL
根据需求而定,如果您不需要attachToRoot,则这是一个方便的辅助方法,或者将getRootView()作为父级传递给该方法。 - Prakash Nadar

11

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

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

4
LayoutInflater.from(context).inflate(R.layout.row_payment_gateway_item, null);

1
鼓励您在代码中提供一些解释性文本。 - HansHirse

3
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );

请使用这个替代方案!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接