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

And*_*oid 32 android drawable

有没有什么办法可以从android中的drawable文件夹中获取图像路径为String.我需要这个,因为我实现了我自己的viewflow,我在sd卡上使用他们的路径显示图像,但我想在没有图像显示时显示默认图像.

任何想法如何做到这一点?

kar*_*ran 47

这些都是方法:

String imageUri = "drawable://" + R.drawable.image;
Run Code Online (Sandbox Code Playgroud)

我测试的其他方式

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();
Run Code Online (Sandbox Code Playgroud)

  • 这样的模式返回FileNotFound异常 (2认同)
  • 这些方法都不适合我。 (2认同)

msh*_*hah 14

根据上述一些答复,我即兴了一点

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

可重用方法

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();
}
Run Code Online (Sandbox Code Playgroud)

样品电话

getURLForResource(R.drawable.personIcon)
Run Code Online (Sandbox Code Playgroud)

加载图像的完整示例

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

您可以将功能getURLForResource移动到Util文件并使其静态,以便可以重用


Sun*_*hoo -6

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

示例代码

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
        }
Run Code Online (Sandbox Code Playgroud)