【问题标题】:Store multi Drawable in an ArrayList with For cycle使用 For 循环将多个 Drawable 存储在 ArrayList 中
【发布时间】:2014-04-04 13:03:32
【问题描述】:

我的项目中有很多图像,名为 image_0、image_1、image_2 ...。目前,为了将它们存储在数组中,我使用

int[] images = {R.drawable.image_0, R.drawable.image_1 ....};

但我有 400 张图片,这在代码中很难看,所以我想使用 for 循环,例如:

ArrayList<Integer> images = new ArrayList<Integer>;
for(int i = 0; i < 400; i++){
   images.add(R.drawable.image_+"i");
}

但它们是 Int 而不是 String.. 我该怎么做?

【问题讨论】:

  • R.drawable.image_0 是字符串还是整数?
  • 为什么将图像文件名存储为整数?
  • @Rahul:这些不是字符串,是 id - 它们是 整数

标签: java android for-loop arraylist drawable


【解决方案1】:

你可以这样处理:

ArrayList<Integer> images = new ArrayList<Integer>;
for(int i = 0; i < 400; i++){
   images.add(getResId(R.drawable.image_+"i", Drawable.class));
}

//method to convert String ID name into Integer value
public static int getResId(String variableName, Class<?> c) {

    try {
        Field idField = c.getDeclaredField(variableName);
        return idField.getInt(idField);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}

原答案是here

【讨论】:

    【解决方案2】:

    这可以使用反射来完成:

    String name = "image_0";
    final Field field = R.drawable.getField(name);
    int id = field.getInt(null);
    Drawable drawable = getResources().getDrawable(id);
    

    或者使用Resources.getIdentifier():

    String name = "image_0";
    int id = getResources().getIdentifier(name, "drawable", getPackageName());
    Drawable drawable = getResources().getDrawable(id);
    

    为了提高内存效率,我还是建议你将 id 存储在 String 数组中,并仅在需要时获取图像。

    【讨论】:

      猜你喜欢
      • 2017-09-08
      • 1970-01-01
      • 2022-11-03
      • 2021-11-18
      • 1970-01-01
      • 2018-02-10
      • 2021-06-16
      • 2014-11-19
      • 2021-06-15
      相关资源
      最近更新 更多