gpt4 book ai didi

android - 从 Resources 对象中检索所有 Drawable 资源

转载 作者:IT老高 更新时间:2023-10-28 22:23:42 26 4
gpt4 key购买 nike

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

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

但是,我想获取所有 Drawable 资源,而我不会事先知道它们的 ID。有没有我可以循环使用的集合,或者是否有一种方法可以获取给定项目中资源的资源 ID 列表?

或者,我有没有办法在 Java 中从 R.drawable 静态类中提取所有属性值?

最佳答案

好的,这感觉有点 hack-ish,但这是我通过 Reflection 想出的。 (请注意,resources 是类 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++) {
final int resourceId;
try {
resourceId = fields[i].getInt(drawableResources);
} catch (Exception e) {
continue;
}
/* make use of resourceId for accessing Drawables here */
}

如果有人有更好的解决方案,可以更好地利用我可能不知道的 Android 调用,我绝对希望看到他们!

关于android - 从 Resources 对象中检索所有 Drawable 资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3221603/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com