0

我需要知道如何检查 R.drawable 中是否存在图像,它必须是动态的,所以我必须使用一个字符串来给我图像的名称。我已经尝试使用 '!=null' 或存在但它没有工作....请帮助!!!!!!!!!

titulo=bundle.getString("titulo");
textView = (TextView) findViewById( R.id.textView1);
textView.setText(titulo);
foto="f"+bundle.getString("numero")+"a";
System.out.println(foto);
flipper =(ViewFlipper) findViewById(R.id.vfFlipper);

这给了我需要的图像名称...

image = new ImageView(this);
image= new ImageView(this);
image.setImageResource(R.drawable.f00a1);
image.setScaleType(ScaleType.FIT_CENTER);
flipper.addView(image);

有了这个我可以使用图像,但我需要使用变量“foto”所以它可以是动态的谢谢!

4

4 回答 4

2

你可以getResources用来获取Resources类的实例。在Resources课堂上,你有getDrawable如果找不到资源,你会得到ResourceNotFoundException这也意味着找不到图像。

所以代码将是这样的

Resource r = getResources();
Bool fileFound = true;
Drawable d = null;
try{
d = r.getDrawable(your_image_id);
}
catch(ResourceNotFoundException e){
fileFound = false;
}
if(findFound){
// Your operations
// set drawable to your imageview.
}
于 2013-10-18T00:37:45.950 回答
2

R 类中的所有内容都是整数 - 您不能创建字符串来表示资源 ID。你能得到的最接近的是使用getResources()然后调用......

getIdentifier(字符串名称,字符串 defType,字符串 defPackage)

...这将允许您根据资源名称找到代表您的资源的整数。

于 2013-10-18T00:44:45.780 回答
1

谢谢你们!我混合了这两个答案,然后..它起作用了!

Resource r = getResources();
Bool fileFound = true;
Drawable d = null;
try{
d = r.getDrawable(getIdentifier(foto1, "drawable", getPackageName());
}
catch(ResourceNotFoundException e){
fileFound = false;
}
if(findFound){
// Your operations
// set drawable to your imageview.
}
于 2013-10-19T14:56:26.643 回答
0
getResources().getIdentifier("icon", "drawable", "your.package.namespace"); 

检查上述语句的非零值。

if(0)
   //does not exists
 else
   //exists
于 2017-08-08T06:26:00.193 回答