2012-01-31 48 views
0

當應用程序啓動時,我有一些圖像保存到Android設備上的目錄中 - 我希望能夠在圖庫中顯示這些圖像,但到目前爲止我還沒有做到。從圖像文件路徑填充Android圖庫?

我按照示例代碼here,但它使用可繪製資源ID而不是文件路徑。我發現this solution與我所尋找的相似,除了它使用ImageView而不是Gallery。

因此,使用ImageView的代碼將是這個樣子:

File imgFile = new File(「/data/data/com.myproject.example/files/someImage.png」); 
if(imgFile.exists()){ 

    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath()); 

    ImageView myImage = (ImageView) findViewById(R.id.imageviewTest); 
    myImage.setImageBitmap(myBitmap); 

} 

上面的代碼工作,但我不知道如何與畫廊做。我一直在尋找答案並嘗試不同的事情,但我對Android的發展並不陌生,我覺得自己有點頭大。

任何幫助表示讚賞。先謝謝你。

回答

0

基本上我想你只需要把你的兩個例子放在一起。

使用HelloGallery例如,作爲一個開始,但是你想改變ImageAdaptergetView()方法中的代碼,以呼籲ImageView而不是setImageResource()setImageBitmap()

您將需要您想要加載的圖像的文件路徑的數組/集合。

0

你需要做的是這樣的:

public ImageAdapter(Context c, int itemId) { 
    context = c; 

    imgArr = GlobalStore.getItem(itemId).getPhotos(); 
    TypedArray attr = context.obtainStyledAttributes(R.styleable.HelloGallery); 
    mGalleryItemBackground = attr.getResourceId(R.styleable.HelloGallery_android_galleryItemBackground, 0); 
    attr.recycle(); 
} 

,你可以看到這基本上是從畫廊教程的副本。在構造函數imgArr變量中加載了一個JPG文件名的數組。這些例如是從數據庫中讀取的。

你有這樣的事情的getView功能

則...

public View getView(int position, View convertView, ViewGroup parent) { 
    ImageView imageView = new ImageView(context); 


    String tmpStr = appContext.getFilesDir() + File.separator + "photos" + File.separator + imgArr.get(position); 
    Bitmap bitmap = BitmapFactory.decodeFile(tmpStr); 
    imageView.setImageBitmap(bitmap); 
    imageView.setLayoutParams(new Gallery.LayoutParams(350, 300)); 
    imageView.setScaleType(ImageView.ScaleType.FIT_XY); 
    imageView.setBackgroundResource(mGalleryItemBackground); 

    return imageView; 
} 

正如你可以看到getFilesDir()得到它存儲文件的應用程序數據的位置,然後讓我們想象一下所有的照片都在「照片「目錄中,您將創建一個路徑並從imgArr數組中附加一個文件名。由於這是每張照片所要求的,您只需使用傳遞的位置變量。

如果您沒有照片陣列,那麼可能的方法是通過閱讀存儲照片的目錄來構建它,將所有文件名加載到數組中,然後執行此操作。

然後,您可以在圖庫教程中完成其餘部分。