Dynamic naming of Resources in Android without getIdentifier

早过忘川 提交于 2019-12-13 03:36:45

问题


I'm using OpenGL ES to make a game in Android. I got some code from a tutorial and I'm trying to change it to suit my app but I'm having a problem. I want to dynamically get an image resource using a string passed into a function as the resource name. I know usually you use getIdentifier() in this case, but that returns an int and I need an input stream. Is there any way of getting an input stream from a resource dynamically?

Alternatively, is there a better way of doing this?

Code below:

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

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

回答1:


yes u can Suppose u have images stored in drawable with naming img1,img2,img3,img4,img5,img6,img7 than first make an array like

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);

if want bitmap image than just add below line

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

if u want other way with less coding than see accepted answer at Other Example



来源:https://stackoverflow.com/questions/11273828/dynamic-naming-of-resources-in-android-without-getidentifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!