好的,经过多次尝试,我终于有了一个可行的例子,我想我会分享它。我的示例查询图像 MediaStore,然后获取每个图像的缩略图以显示在视图中。我正在将图像加载到 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 查询来过滤特定文件夹中的图像文件列表。