Luk*_*kap 176 service android toast android-context layout-inflater
需要导入什么或如何在活动以外的地方调用布局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();
}
Run Code Online (Sandbox Code Playgroud)
我getLayoutInflater只能在活动中打电话,这是限制吗?如果我想创建自定义对话框并且我想为它充气视图,或者如果我想要从服务中显示自定义视图的Toast消息,我只有来自服务的上下文我没有任何活动该怎么办?但我想显示自定义消息.
我需要在代码中不在activity类中的地方使用inflater.
我怎样才能做到这一点 ?
kas*_*rch 380
您可以使用此外部活动 - 您只需提供Context:
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
Run Code Online (Sandbox Code Playgroud)
然后,要检索不同的小部件,您需要对布局进行扩充:
View view = inflater.inflate( R.layout.myNewInflatedLayout, null );
Button myButton = (Button) view.findViewById( R.id.myButton );
Run Code Online (Sandbox Code Playgroud)
编辑截至2014年7月
Davide 关于如何获得它的答案LayoutInflater实际上比我的更正确(尽管仍然有效).
Dav*_*ide 246
要么 ...
LayoutInflater inflater = LayoutInflater.from(context);
Run Code Online (Sandbox Code Playgroud)
使用上下文对象,您可以从以下代码中获取LayoutInflater
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
141167 次 |
| 最近记录: |