从Resources对象检索所有Drawable资源

在我的Android项目中,我想遍历整个Drawable资源集合。通常,您只能使用以下方式通过其ID检索特定资源:


InputStream is = Resources.getSystem().openRawResource(resourceId)

但是,我想获取所有Drawable我事先不知道其ID的资源。给定项目中的资源后,是否有我可以循环访问的集合或一种获取资源ID列表的方法?


或者,在Java中,有没有一种方法可以从R.drawable静态类中提取所有属性值?


茅侃侃
浏览 534回答 3
3回答

沧海一幻觉

如果发现自己想要这样做,则可能是在滥用资源系统。看一下资产,以及AssetManager是否要遍历.apk中包含的文件。

HUWWW

好的,这感觉有点骇人听闻,但这就是我通过Reflection提出的。(请注意,这resources是class的实例android.content.res.Resources。)final R.drawable drawableResources = new R.drawable();final Class<R.drawable> c = R.drawable.class;final Field[] fields = c.getDeclaredFields();for (int i = 0, max = fields.length; i < max; i++) {&nbsp; &nbsp; final int resourceId;&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; resourceId = fields[i].getInt(drawableResources);&nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; }&nbsp; &nbsp; /* make use of resourceId for accessing Drawables here */}如果有人拥有更好的解决方案,可以更好地利用我可能不知道的Android通话,那么我肯定希望看到他们!

慕村9548890

我对Matt Huggins做出了很好的回答,并对其进行了重构以使其更加通用:public static void loadDrawables(Class<?> clz){&nbsp; &nbsp; final Field[] fields = clz.getDeclaredFields();&nbsp; &nbsp; for (Field field : fields) {&nbsp; &nbsp; &nbsp; &nbsp; final int drawableId;&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; drawableId = field.getInt(clz);&nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; /* make use of drawableId for accessing Drawables here */&nbsp; &nbsp; }&nbsp; &nbsp;}用法:loadDrawables(R.drawable.class);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android