Android访问drawable文件夹

标签 android image drawable

我在 drawable 文件夹中放置了 10 张图像,并创建了一个自定义类,其中的实例包含一个 id Integer,该 id 整数应该将其引用到 draw 文件夹中的图像。现在我想知道如何一次设置这些 id-s,而不是一个一个地设置。相反:

object[0].setImage(R.drawable.image1);
object[1].setImage(R.drawable.image2);

我想用循环来做这个,但是怎么做呢?

最佳答案

众所周知,

Drawable id 是在 final class R 的静态类中生成的。所以直接用反射读取这些静态属性的值就可以了。如果您想获取 Int id,请使用此代码:

    for(Field f : R.drawable.class.getDeclaredFields()){
        if(f.getType() == int.class){
            try {
                   int id = f.getInt(null);
                   // read the image from the id
            } catch (IllegalAccessException e) {
               e.printStackTrace();
            } catch (IllegalArgumentException e){
                e.printStackTrace();
            }
        }
    }

或者,如果您想直接通过图像名称进行搜索,您可能会对以下字段的名称属性感兴趣:

    for(Field f : R.drawable.class.getDeclaredFields()){
        if(f.getType() == int.class){
            try {
                String name = f.getName();
                // rest of the code handling file loading
                } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    }

关于Android访问drawable文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25632984/

相关文章:

android - 在同一个应用程序中强制执行 android 权限

Android通过intent发送Twitter私信

android - 有关如何执行延迟后台工作的即时应用建议

Android放大图标drawable的透明背景

android - 以编程方式更改按钮可绘制

java - java 中的 JSON.stringify - android

ios - 如何同时更改 iOS 按钮的图像和文本?

c# - C# 上的 DrawString 文本太粗

android - 在Android上使用Camera2进行OpenCV图像处理

安卓开发 : Unable to create an icon @drawable/ic_action_search