【问题标题】:drawable getResources().getIdentifier problemdrawable getResources().getIdentifier 问题
【发布时间】:2011-11-13 19:35:50
【问题描述】:

这是我第一次来这里(我觉得这个网站非常有用)。我是 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 文件夹中。 任何想法为什么当我尝试传递他们的名字并从资源中获取它们时没有加载图像?

【问题讨论】:

    标签: android


    【解决方案1】:

    如果你这样做会怎样:

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

    【讨论】:

      【解决方案2】:

      这是一个辅助函数

      public static int getDrawable(Context context, String name)
      {
          Assert.assertNotNull(context);
          Assert.assertNotNull(name);
      
          return context.getResources().getIdentifier(name,
                  "drawable", context.getPackageName());
      }
      

      【讨论】:

      • 有效!。非常感谢!
      猜你喜欢
      • 1970-01-01
      • 2023-02-01
      • 2012-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-25
      相关资源
      最近更新 更多