android - 使用 gridview 显示 SDCard 上特定文件夹中的图像

标签 android gridview uri android-sdcard bitmapfactory

我正在尝试创建一个 gridview,其中加载了位于 SDCard 上的特定文件夹中的图像。文件夹的路径是已知的 ("/sdcard/pictures") ,但在我在网上看到的示例中,我不确定如何或在何处指定我要从中加载图像的图片文件夹的路径。我已经阅读了许多教程,甚至是 developer.android.com 上的 HelloGridView 教程,但这些教程并没有告诉我我在寻找什么。

到目前为止我读过的每个教程都有:

A) 从/res 文件夹中将图像作为 Drawable 调用,并将它们放入要加载的数组中,根本不使用 SDCard。

B) 使用 MediaStore 访问了 SDCard 上的所有 图片,但未指定如何设置文件夹的路径我想显示图片形式

C) 建议使用 BitmapFactory,我完全不知道如何使用它。

如果我以错误的方式解决这个问题,请告诉我并指导我采用正确的方法来完成我想做的事情。

最佳答案

好的,经过多次反复尝试,我终于有了一个可行的示例,我想我会分享它。我的示例查询图像 MediaStore,然后获取每个图像的缩略图以显示在 View 中。我正在将我的图像加载到 Gallery 对象中,但这不是此代码工作的必要条件:

确保在类级别为列索引定义了 Cursor 和 int,以便 Gallery 的 ImageAdapter 可以访问它们:

private Cursor cursor;
private int columnIndex;

首先,获取位于文件夹中的图像 ID 光标:

Gallery g = (Gallery) findViewById(R.id.gallery);
// request only the image ID to be returned
String[] projection = {MediaStore.Images.Media._ID};
// Create the cursor pointing to the SDCard
cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
        projection, 
        MediaStore.Images.Media.DATA + " like ? ",
        new String[] {"%myimagesfolder%"},  
        null);
// Get the column index of the image ID
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
g.setAdapter(new ImageAdapter(this));

然后,在 Gallery 的 ImageAdapter 中,获取要显示的缩略图:

public View getView(int position, View convertView, ViewGroup parent) {
    ImageView i = new ImageView(context);
    // Move cursor to current position
    cursor.moveToPosition(position);
    // Get the current value for the requested column
    int imageID = cursor.getInt(columnIndex);
    // obtain the image URI
    Uri uri = Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(imageID) );
    String url = uri.toString();
    // Set the content of the image based on the image URI
    int originalImageId = Integer.parseInt(url.substring(url.lastIndexOf("/") + 1, url.length()));
    Bitmap b = MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(),
                    originalImageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
    i.setImageBitmap(b);
    i.setLayoutParams(new Gallery.LayoutParams(150, 100));
    i.setScaleType(ImageView.ScaleType.FIT_XY);
    i.setBackgroundResource(mGalleryItemBackground);
    return i;
}

我想这段代码最重要的部分是 managedQuery,它演示了如何使用 MediaStore 查询来过滤特定文件夹中的图像文件列表。

关于android - 使用 gridview 显示 SDCard 上特定文件夹中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5039779/

相关文章:

c# - 在 gridview 中如何为按钮使用 rowcommand 事件

c# - foreach 循环无法转换但手动转换和 for 循环工作

android - 程序类型已经存在 : android. support.v4.app.BackStackState$1

java - 强制关闭!!用于分配 RGB 值 0-255 中的随机颜色的按钮

c# - 如何在ASP.NET C#的Gridview中获取并显示特定的值

c# - 确定路径字符串是本地机器还是远程机器的方法

codeigniter - 在 CodeIgniter 中的 Controller URI 段之前传递变量

c# - 重绘图像 WPF

Android: java.lang.VerifyError 因为泛型类

android - 将彩信流转换为任何 Android 格式