Android 从布局获取ImageView并设置图像时出错
您好,我有一个anroid应用程序,我想从布局中获取ImageView并设置图像,但我得到了错误:android.content.res.Resources$NotFoundException:资源ID 0x0 我尝试日志,它将显示uri,imageResource也为0 ps:Log for building.getImage的值是church,但是,我的drawable文件夹中有church.png 如果你能帮忙,我将不胜感激 代码如下:Android 从布局获取ImageView并设置图像时出错,android,Android,您好,我有一个anroid应用程序,我想从布局中获取ImageView并设置图像,但我得到了错误:android.content.res.Resources$NotFoundException:资源ID 0x0 我尝试日志,它将显示uri,imageResource也为0 ps:Log for building.getImage的值是church,但是,我的drawable文件夹中有church.png 如果你能帮忙,我将不胜感激 代码如下: /* Extract the Building's
/* Extract the Building's object to show */
Buildings building = (Buildings) getItem(position);
ImageView imageCity = (ImageView) convertView.findViewById(R.id.ImageCity);
String uri = "drawable/" + building.getImage();
int imageResource = context.getResources().getIdentifier(building.getImage(), "drawable", context.getPackageName());
Log.e("URI", uri);
Log.e("context.getPackag", context.getPackageName());
Log.e("imageResource", String.valueOf(imageResource));
Drawable image = ContextCompat.getDrawable(this.context, imageResource);
imageCity.setImageDrawable(image);
getIdentifier的第一个参数是资源的名称,您正在查找该资源的id,没有扩展名。在您的例子中,这是building.getImage,而不是uri,uri是drawable/和图像名称的串联。您希望在drawable中查找它的事实在getIdentifier的第二个参数中指定。从
int imageResource = context.getResources().getIdentifier(uri, "drawable", context.getPackageName());
到
谢谢,但仍然出现相同的错误,ImageResource为0 building.getImage的值是多少?您是否在drawable-*/文件夹中有它?它是图像,是的,我有它,我使用日志,它将显示图像的名称(在本例中为church,但没有扩展名)。png是否应将其添加到uri中?总结一下。building.getImage返回church,您的一个可绘图文件夹中有一个church.png,您更改了代码以反映我建议的更改。我说得对吗?让我们来。
int imageResource = context.getResources().getIdentifier(building.getImage(), "drawable", context.getPackageName());