Android从drawable获取图像路径作为字符串

Android从drawable获取图像路径作为字符串,android,drawable,Android,Drawable,是否有任何方法,我可以从android中的drawable文件夹获取图像路径作为字符串。我之所以需要它,是因为我实现了自己的viewflow,在这里我使用sd卡上的路径来显示图像,但我想在没有图像显示时显示默认图像 有什么办法吗?首先检查SD卡中是否存在该文件。如果SD卡中不存在该文件,则可以使用setImageResource()方法设置图像,并从drawable文件夹传递默认图像 示例代码 File imageFile = new File(absolutepathOfImage);//ab

是否有任何方法,我可以从android中的drawable文件夹获取图像路径作为字符串。我之所以需要它,是因为我实现了自己的viewflow,在这里我使用sd卡上的路径来显示图像,但我想在没有图像显示时显示默认图像


有什么办法吗?

首先检查SD卡中是否存在该文件。如果SD卡中不存在该文件,则可以使用setImageResource()方法设置图像,并从drawable文件夹传递默认图像

示例代码

File imageFile = new File(absolutepathOfImage);//absolutepathOfImage is absolute path of image including its name
        if(!imageFile.exists()){//file doesnot exist in SDCard

        imageview.setImageResource(R.drawable.defaultImage);//set default image from drawable folder
        }
这些都是方法:

String imageUri = "drawable://" + R.drawable.image;
我测试的其他方法

Uri path = Uri.parse("android.resource://com.segf4ult.test/" + R.drawable.icon);
Uri otherPath = Uri.parse("android.resource://com.segf4ult.test/drawable/icon");

String path = path.toString();
String path = otherPath .toString();

如果您计划从其路径获取图像,最好使用资源,而不是试图找出可绘制文件夹的路径

    InputStream stream = getAssets().open("image.png");
    Drawable d = Drawable.createFromStream(stream, null);

根据上面的一些回答,我临时做了一点

创建此方法并通过传递资源调用它

可重复使用的方法

public String getURLForResource (int resourceId) {
    //use BuildConfig.APPLICATION_ID instead of R.class.getPackage().getName() if both are not same
    return Uri.parse("android.resource://"+R.class.getPackage().getName()+"/" +resourceId).toString();
}
示例通话

getURLForResource(R.drawable.personIcon)
加载图像的完整示例

String imageUrl = getURLForResource(R.drawable.personIcon);
// Load image
 Glide.with(patientProfileImageView.getContext())
          .load(imageUrl)
          .into(patientProfileImageView);

您可以将函数getURLForResource移动到一个Util文件中,并将其设置为静态,以便可以重用它

我认为您无法将其作为
String
获取,但可以通过获取资源
id
将其作为
int
获取:

int resId = this.getResources().getIdentifier("imageNameHere", "drawable", this.getPackageName());

正如我读到的[here][1]这是不可能的,因为文件在apk中。[1] 这是正确的答案。您好,如何显示路径中的图像???我得到的文件格式不受支持的错误与所有这些。这种模式返回FileNotFound例外唯一的答案,对我有效。这个合成的URL在不同提供商的Android版本之间的兼容性如何?图片不以上述方式显示。@AshishJain,你需要分享更多信息,比如Android版本;图像类型是什么,图像放置的位置是否有错误,等等。我正在为Android所有版本(如8、9和10)尝试相同的代码,并传递向量图像(.xml),但它没有显示在我的自定义recyclerview上。@AshishJain上述代码已经过测试,仅与常规图像兼容,而不是SVG