在Android的资源动态无命名则getIdentifier [英] Dynamic naming of Resources in Android without getIdentifier

查看:99
本文介绍了在Android的资源动态无命名则getIdentifier的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的OpenGL ES以使Android的游戏。我从一个教程约code和我试图去改变它适合我的应用程序,但我有一个问题。我想用传递给函数的资源名称的字符串动态获取的图像资源。通常我知道你在这种情况下使用则getIdentifier(),但返回一个int,我需要的输入流。有没有从资源动态?

获得的输入流中的任何方式

另外,有这样做的更好的办法?

code如下:

  InputStream为= mContext.getResources()openRawResource(R.drawable< imagename>)。位图位图;
尝试{
      位= BitmapFactory.de codeStream(是);
}
最后{
      尝试{
            is.close();
      }
      赶上(IOException异常五){
            e.printStackTrace();
      }
}


解决方案

是U可以假设u必须与命名IMG1,IMG2,IMG3,IMG4,IMG5,img6,IMG7比存储在图像绘制
首先要像

数组

 的String [] = imgarray {IMG1,IMG2,IMG3,IMG4,IMG5,img6,IMG7};
公共静态字符串PACKAGE_NAME;
PACKAGE_NAME = getApplicationContext()getPackageName()。
随机R =新的随机();
INT N = r.nextInt(imgarray.length());
INT渣油= getResources()则getIdentifier。(PACKAGE_NAME +:绘/+ imgarray [N],NULL,NULL);
imageview.setImageResource(渣油);

如果要位图图像,不仅仅是在下面添加行

 位图BM = BitmapFactory.de codeResource(getResources(),渣油);

如果ü希望用更少的编码其他方式比看到<一个公认的答案href=\"http://stackoverflow.com/questions/10135713/display-a-random-image-when-a-button-is-clicked/10135994#10135994\">Other例如

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

解决方案

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

这篇关于在Android的资源动态无命名则getIdentifier的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆