【问题标题】:Dynamic naming of Resources in Android without getIdentifier没有getIdentifier的Android中资源的动态命名
【发布时间】:2012-06-30 11:47:12
【问题描述】:

我正在使用 OpenGL ES 在 Android 中制作游戏。我从教程中获得了一些代码,我正在尝试对其进行更改以适合我的应用程序,但我遇到了问题。我想使用传递给函数的字符串作为资源名称来动态获取图像资源。我知道通常你在这种情况下使用 getIdentifier() ,但它返回一个 int 并且我需要一个输入流。有没有办法从资源中动态获取输入流?

或者,有没有更好的方法来做到这一点?

代码如下:

InputStream is = mContext.getResources().openRawResource(R.drawable.<imagename>);

Bitmap bitmap;
try {
      bitmap = BitmapFactory.decodeStream(is);
}
finally {
      try {
            is.close();
      } 
      catch (IOException e) {
            e.printStackTrace();
      }
}

【问题讨论】:

  • 我已经更新了我的答案检查它

标签: java android opengl-es


【解决方案1】:

是的,你可以假设你将图像存储在 drawable 中,命名为 img1,img2,img3,img4,img5,img6,img7 首先制作一个类似

的数组
String[] imgarray={"img1","img2","img3","img4","img5","img6","img7"};
public static String PACKAGE_NAME ;
PACKAGE_NAME=getApplicationContext().getPackageName();
Random r = new Random();
int n=r.nextInt(imgarray.length());
int resID = getResources().getIdentifier( PACKAGE_NAME+":drawable/" +imgarray[n] , null, null);  
imageview.setImageResource(resID);

如果想要位图图像而不是只添加以下行

Bitmap  bm = BitmapFactory.decodeResource(getResources(),resID);

如果您想要其他编码更少的方式,请参阅Other Example 接受的答案

【讨论】:

  • 我如何从中获取输入流,因为我需要它来制作位图?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多