Android drawable getResources().getIdentifier 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3276968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
drawable getResources().getIdentifier problem
提问by NickOpris
this is my first time here (I find the website very useful). I'm new to android and I need to find out why I can't dynamically load images in my list view.
这是我第一次来这里(我发现该网站非常有用)。我是 android 新手,我需要找出为什么我不能在列表视图中动态加载图像。
I have three arrays of strings:
我有三个字符串数组:
private String lv_arr[]={"News",
"Events",
"Other"};
private String lv_arr_d[]={"Get the latest news",
"Latest events",
"Other description here"};
private String lv_arr_icons[]={"news", "events", "other"};
My list displays an icon to the left and two lines of text to the right in each list item. It works ok when I hard code the name of the image (e.g. news).
我的列表在每个列表项的左侧显示一个图标,在右侧显示两行文本。当我对图像的名称(例如新闻)进行硬编码时,它可以正常工作。
ArrayList <HashMap <String, Object>> users =
new ArrayList <HashMap <String, Object>> ();
int l = lv_arr.length;
for (int i = 0; i <l; i++) {
HashMap <String, Object> user = new HashMap <String, Object> ();
//get icons
String uri = "drawable/"+lv_arr_icons[i];
user.put ( "icon", (Drawable)getResources().getDrawable(
getResources().getIdentifier(uri, null, getPackageName())));
//the above works ok if i set R.drawable.news
user.put ( "label", lv_arr[i].toString());
user.put ( "description", lv_arr_d[i].toString());
users.add (user);
}
String[] names = {"icon", "label", "description"};
int[] views = {R.id.icon, R.id.label, R.id.description};
SimpleAdapter saImageItems = new SimpleAdapter(this.getApplicationContext(),
users, R.layout.optionslistitem, names, views);
lv1.setAdapter(saImageItems); //lv1 is my ListView
All images are in the drawable folder. Any ideas why no image loads when i try to pass on their name and get them from resources?
所有图像都在 drawable 文件夹中。当我尝试传递他们的名字并从资源中获取它们时,为什么没有图像加载的任何想法?
回答by Cristian
What if you just do this:
如果你只是这样做怎么办:
user.put ( "icon", getResources().getIdentifier(uri, "drawable", getPackageName()));
回答by Pedro Rainho
here is an helper function
这是一个辅助函数
public static int getDrawable(Context context, String name)
{
Assert.assertNotNull(context);
Assert.assertNotNull(name);
return context.getResources().getIdentifier(name,
"drawable", context.getPackageName());
}