如何在可绘制文件夹中找到图像的文件路径作为字符串?

How do I find the filepath to an image in the drawable folder as a string?

我想找到以易于解析的格式存储在 res/drawable/ 中的图像的文件路径。例如,drawable://2131099733 很难解析,但 /drawable/1.jpg 很容易解析。我在下面尝试过的方法不起作用,但这将是实现它的理想方法。

我想要它的原因是因为我将拥有名为 1.jpg2.jpg 的图像,然后我将能够使用字符串连接轻松地将其加载到 ImageView.

File imgFile = new File("/res/drawable/adorable-animal-cat-20787.jpg");

这(使用 File class)永远不会起作用,因为在运行时可绘制对象被打包在 APK 中。

现在,要在运行时(通过代码)将可绘制对象加载到 ImageView 中,只需执行以下操作:

imageView.setBackgroundResource(R.drawable.drawable_resource_identifier);

但是,您需要从字符串值加载可绘制对象,您可以使用 Resources class 来解析可绘制对象的标识符...

int resID = context.getResources().getIdentifier("drawable_name", "drawable", getPackageName());
imageView.setImageResource(resID);