在 Android R.drawable.<filename> 中使用动态文件名

Use dynamic filename in Android R.drawable.<filename>

我正在尝试动态构建 Android 中图像的文件名以在 R.drawable 中使用。条款。

这是我的代码:

    imgHouse = (ImageView)findViewById(R.id.imageView);
    strHouseNameImageFile = strHouseName + ".png";
    imgHouse.setBackgroundResource(R.drawable.<filename>);

在上面的最后一行中,我真的希望它是房屋名称和 .png 的组合,但我不确定如何将 R.drawable 将使用的字符串放在一起。

我可以在最后一行做这样的事情吗,现在在 Android Studio 中出现错误: imgHouse.setBackgroundResource(strHouseNameImageFiles);

如有任何帮助,我们将不胜感激。

谢谢

int iconResId = getResources().getIdentifier(strHouseName, "drawable",getPackageName());

imgHouse.setImageResource(iconResId);

您尝试设置后台资源的方式可能无法正常工作,因为 R class 是在编译时生成的。 R.drawable.*** 实际上是一个在编译时生成的整数。与您的问题最接近的可能是 post : Dynamic loading of images R.Drawable using variable