drawable getResources().getIdentifier问题

12

这是我第一次来到这里(我发现这个网站非常有用)。我是Android新手,需要找出为什么无法在我的列表视图中动态加载图像。

我有三个字符串数组:

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"};

我的列表在每个列表项的左侧显示一个图标,在右侧显示两行文本。当我硬编码图像名称时(例如新闻),它可以正常工作。

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

所有图片都在drawable文件夹中。 我尝试通过名称从资源中获取图像,但为什么没有图像加载呢?

2个回答

29

如果你只是这样做会怎样:

user.put ( "icon", getResources().getIdentifier(uri, "drawable", getPackageName()));

11

这是一个辅助函数

public static int getDrawable(Context context, String name)
{
    Assert.assertNotNull(context);
    Assert.assertNotNull(name);

    return context.getResources().getIdentifier(name,
            "drawable", context.getPackageName());
}

运行正常!非常感谢! - KinGPinG

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