如何创建动态解码资源



我想创建一个动态decoderresource来使用对象中的所有图像。

这是我的代码:

for(int i=42; i<55; i++) {
            bitmap = BitmapFactory.decodeResource(context.getResources(),
                    Integer.parseInt("R.drawable.a"+i));
        }

我想要得到文件

R.drawable.a43 to a54

是否可以为decoderresource创建一个循环?

检索'R.drawable '的资源ID。我们可以这样动态地使用Resources.getIdentifier:

final String pkg = context.getPackageName();
final Resources resources = context.getResources();
...
int num = ...; /* between 43 and 54 */
final int id = resources.getIdentifier("a" + num, "drawable", pkg);

您可以使用类似于您现在使用的循环将这些存储在List中,只是稍微修改了边界:

final String pkg = context.getPackageName();
final Resources resources = context.getResources();
final List<Bitmap> bitmaps = new ArrayList<Bitmap>();
for (int i = 43; i <= 54; ++i) {
  /* decode bitmap with id R.drawable.a{i} */
  final Bitmap bitmap = BitmapFactory.decodeResource(resources,
      resources.getIdentifier("a" + i, "drawable", pkg));
  bitmaps.add(bitmap);
}
/* now bitmaps contains the Bitmaps */

最新更新