2016-06-13 96 views
1

我正在使用Android Studio構建我的應用程序,此應用程序可以將圖像從樹莓上傳到我的模擬器。它工作正常。我現在想做的就是上傳這張圖片,直接顯示給用戶,而不用在圖庫中搜索。我想創建另一個類,並在我的xml文件中將此圖像設置爲背景圖像,但這太像我每次想從樹莓上傳圖像時都必須創建另一個類。 有人可以幫助我。謝謝允許在Android Studio中顯示圖像的按鈕

回答

0

如果我正確理解你的問題,你想從Android文件系統加載一個圖像到你的應用程序並顯示給用戶。

Drawable,Android的廣義圖像類,允許您通過Drawable#createFromPath從文件加載。

This SO question表明Drawable#createFromPath不與file://路徑開始工作,所以根據您的使用情況,你可能想先與Uri#parse/Uri#getPath

一旦你有一個Drawable,您可以通過以下兩種方式之一顯示出來:把一個ImageView在您的應用程序並調用其setImageDrawable方法,或者設置Drawable爲背景圖像通過View#setBackground(注意:setBackground在只增加API 16 - 在以前的版本中,您應該致電View#setBackgroundDrawable)。

把所有的這一起,我們最終以下(未經測試):

private void loadImage(String imagePath) { 
    Uri imageUri; 
    String fullImagePath; 
    Drawable image; 
    ImageView imageDisplay; 

    imageUri = Uri.parse(imagePath); 
    fullImagePath = imageUri.getPath(); 
    image = Drawable.createFromPath(fullImagePath); 

    imageDisplay = (ImageView) findViewById(R.id.imageDisplay); 
    /*if image is null after Drawable.createFromPath, this will simply 
     clear the ImageView's background */ 
    imageDisplay.setImageDrawable(image); 

    /*if you want the image in the background instead of the foreground, 
     comment the line above and uncomment this bit instead */ 
    //imageDisplay.setBackground(image); 
} 

你應該能夠修改此與任何View工作只是通過用適當的替代imageDisplay的聲明的類型View鍵入並更改findViewById。只要確保你打電話setBackground,而不是setImageDrawable,對於非ImageViewView

+0

謝謝你的回答,它似乎是正確的,但它說不能解決imageDisplay在這一個:imageDisplay =(ImageView)findViewById(R.id.imageDisplay); –

+0

'R.id.imageDisplay'是'ImageView'的ID。你需要用你給自己的'ImageView'來替換它。 – computerfreaker

+0

thnx男人,它完美的作品。 –