在不在 Activity 中的地方调用 getLayoutInflater()
需要导入什么或者如何在 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 消息,我只有来自服务的上下文,我没有任何活动,该怎么办但我想显示自定义消息。
我需要在代码中不属于活动类的地方使用充气机。
我该怎么做?
What does need to be imported or how can I call the Layout inflater in places other than 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();
}
I am able to call getLayoutInflater
only in activity, is that an restriction? What if I want to create custom dialog and I want to inflate view for it, or what if I want to have Toast message with custom view that is shown from a service, I only have the context from the service I do not have any activity but I want to show custom message.
I need the inflater in places in the code that isn't in the activity class.
How can I do this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用此外部活动 - 您所需要的只是提供一个
上下文
:然后要检索不同的小部件,您可以膨胀一个布局:
截至 2014 年 7 月编辑
Davide 的 关于如何获取
LayoutInflater
的答案实际上比我的更正确(仍然有效) 尽管)。You can use this outside activities - all you need is to provide a
Context
:Then to retrieve your different widgets, you inflate a layout:
EDIT as of July 2014
Davide's answer on how to get the
LayoutInflater
is actually more correct than mine (which is still valid though).或者 ...
Or ...
或
View.inflate(上下文、布局、父级)
or
View.inflate(context, layout, parent)
使用上下文对象,您可以从以下代码中获取 LayoutInflater
Using context object you can get LayoutInflater from following code
用这个代替吧!
Use this instead!