2012-08-03 27 views
0

我有一張圖片保存在/data/data/my.package.name/files/mypicture.png,我想加載它在一個佈局。如何將私人文件中的圖片加載到佈局(Android)中?

我試過這個,但它不起作用。

File filePath = getFileStreamPath("pictureIWouldLikeToLoad.png"); 
ImageView img = new ImageView(getApplicationContext()); 
img.setImageDrawable(Drawable.createFromPath(filePath.toString())); 
ViewGroup picturesLayout = (ViewGroup) findViewById(R.id.layout_pictures_area); 
picturesLayout.addView(imgView); 

我不明白它是如何工作的,有人可以解釋我爲什麼嗎?那麼我想怎麼做呢?我需要一個內容提供者嗎?有沒有更簡單的方法來做到這一點?

回答

1

所以我成功了。也許它可以改善,但這是實際工作的東西:

FileInputStream inputStream = openFileInput("my_image.png"); 
BufferedInputStream bufferedInput = new BufferedInputStream(inputStream);      
Bitmap bmp = BitmapFactory.decodeStream(bufferedInput); 
ImageView imgView = (ImageView) findViewById(R.id.my_imageview); 
imgView.setImageBitmap(bmp); 
bufferedInput.close(); 
inputStream.close(); 
1

,你應該在你的XML定義ID到要更改

<ImageView 
android:id="@+id/awesome_image" 
. 
. 
. 
/> 

,那麼你應該將圖像文件轉換成位圖對象

File file = new File("/data/data/my.package.name/files/mypicture.png"); 
Bitmap bmp = BitmapFactory.decodeFile(file); 

最後你得到的ImageView對象的圖像並設置其位圖

ImageView imageView = (ImageView) findViewById(R.id.awesome_image); 
imageView.setImageBitmap(bmp); 
+0

有什麼區別?兩者通常都有效,不是嗎? – cleroo 2012-08-06 07:36:23

+0

順便說一句,你可以直接給'decodeFile'方法這樣的路徑:'Bitmap bmp = BitmapFactory.decodeFile(「/ data/data/my.package.name/files/mypicture.png」);'。 – cleroo 2012-08-06 07:43:47

+0

我把自己的答案,謝謝無論如何幫助! – cleroo 2012-08-06 08:35:11

相關問題