2011-12-22 124 views
26

有沒有什麼辦法可以從android中的可繪製文件夾獲取圖像路徑作爲字符串。我需要這個,因爲我實現了我自己的視圖流,通過在sd卡上使用它們的路徑顯示圖像,但是我想在沒有圖像顯示時顯示默認圖像。Android獲取可繪製的圖像路徑作爲字符串

任何想法如何做到這一點?

+1

當我讀到[這裏] [ 1]這是不可能的,因爲這些文件在apk中。 [1]:http://stackoverflow.com/questions/6301493/android-get-path-of-resource – 2012-11-03 17:44:22

+0

這是正確的答案。 http://stackoverflow.com/a/25758286/7795876 – Hangman 2017-04-05 13:02:51

回答

-6

這樣你就可以到達drawable文件夾中的特定圖像。獲取資源,然後指定你想要的形象進入:

Resources res = getResources(); 
Drawable drawable = res.getDrawable(R.drawable.myimage); 

欲瞭解更多信息,請參閱Drawable resources

+0

這不是回答這個問題。看起來他知道如何從可繪製文件夾中獲取圖像,但是R.drawable.myimage返回一個int值,並且他正在查找Resource文件夾的字符串路徑。 – lagos 2014-10-21 09:37:45

-5

首先檢查文件是否存在於SDCard中。如果在SD卡上的文件存在多年平均值,那麼你可以從繪製文件夾

示例代碼

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 
     } 
34

設置使用setImageResource(圖)methodand通過默認的圖像這些都是方法:

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(); 
+0

我收到的文件格式不支持所有這些錯誤。 – NarendraJi 2016-06-02 08:37:19

+1

這樣的模式返回FileNotFound異常 – 2016-09-22 16:32:12

+0

第一種方法不起作用 – mshah 2018-01-16 05:49:52

0

如果你打算從它的圖像路徑,最好使用Assets而不是試圖找出可繪製文件夾的路徑。

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

基礎上,一些上述答覆我臨時有點

創建這個方法,並通過將您的資源

可重複使用的方法

public String getURLForResource (int resourceId) { 
    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移動到一個實用程序文件,並使其靜態所以它可以重複使用