Displaying images from a specific folder on the SDCard using a gridview

后端 未结 6 1813
北海茫月
北海茫月 2020-11-27 17:26

I\'m attempting to create a gridview that is loaded with images from a specific folder that resides on an SDCard. The path to the folder is known, (\"/sdcard/pictures\") , b

6条回答
  •  盖世英雄少女心
    2020-11-27 18:18

    You need to do a few more steps than the GridView tutorial on developer.android.com. Using the following tutorial http://developer.android.com/resources/tutorials/views/hello-gridview.html

    You'll want to add a method to create ImageView's of the files from your sd card:

    Create/add a Vector to your class variables (to hold a list of ImageViews):

    private Vector mySDCardImages;
    

    Initialize the vector:

    mySDCardImages = new Vector();
    

    Create a method to load images:

    List drawablesId = new ArrayList();
    int picIndex=12345;
    File sdDir = new File("/sdcard/pictures");
    File[] sdDirFiles = sdDir.listFiles();
    for(File singleFile : sdDirFiles)
    {
       ImageView myImageView = new ImageView(context);
       myImageView.setImageDrawable(Drawable.createFromPath(singleFile.getAbsolutePath());
       myImageView.setId(picIndex);
       picIndex++;
       drawablesId.add(myImageView.getId());
       mySDCardImages.add(myImageView);
    }
    mThumbIds = (Integer[])drawablesId.toArray(new Integer[0]);
    

    Then down in your ImageAdapter method, change

    imageView.setImageResource(mThumbIds[position]);
    

    to

    imageView.setImageDrawable(mySDCardImages.get(position).getDrawable());
    

    Remove from the ImageAdapter the initialization of mThumbIds. (it should be up with the definition of mySDCardImages. Accessible to both class methods.)

    (Quick and dirty version) Make sure to test your path, etc and catch any Exceptions.

提交回复
热议问题