我试图围绕这个问题来解决这个问题。我有一些代码使用CursorLoader从SD卡中查询图像,并在SimpleCursorAdapter的帮助下将它们显示在GridView中。我在网上跟随了一些例子,并通读了文档。我知道我有一些事情是正确的。该代码运行时没有任何错误,但是我无法获取要在网格上显示的缩略图。以下是到目前为止,我已经得到了代码:从SDCard查询图像并将其显示在GridView中
GalleryFragment.java
public class GalleryFragment extends Fragment {
private SimpleCursorAdapter adapter;
public static final int PHOTO_LIST_ID = 0x01;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
// Bind adapter to grid
setupCursorAdapter();
// Initialize the loader with a special ID and the defined callbacks
getLoaderManager().initLoader(PHOTO_LIST_ID,
new Bundle(), imageLoader);
GridView gridView = (GridView) view.findViewById(R.id.gridView);
gridView.setAdapter(adapter);
return view;
}
private void setupCursorAdapter() {
String[] from = {MediaStore.Images.Thumbnails.DATA};
int[] to = {R.id.imageView};
adapter = new SimpleCursorAdapter(getActivity().getBaseContext(),
R.layout.gallery_image_item,
null, from, to,
0);
}
private LoaderManager.LoaderCallbacks<Cursor> imageLoader =
new LoaderManager.LoaderCallbacks<Cursor>() {
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// Define the columns to retrieve
String[] projection = {MediaStore.Images.Thumbnails._ID,
MediaStore.Images.Thumbnails.DATA};
return new CursorLoader(getActivity(),
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
};
}
fragment_gallery.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="edu.sfsu.csc780.pictachio.GalleryFragment">
<GridView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/gridView"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"/>
</LinearLayout>
gallery_image_item.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:padding="10dp"
android:adjustViewBounds="true"
android:contentDescription="ImageView" />
</FrameLayout>
我在很多地方看, RecyclerView是推荐的方法而不是GridView。我已经对它进行了一次尝试,但我不知道要为此创建什么样的模型。任何帮助,这是表示赞赏。谢谢。
在这个问题的代码为我工作,我得到它运行为了回答这个问题(尽管使用一个库):http://stackoverflow.com/questions/30407581/get-mediastore-path-of-a - 特定文件夹 –
有趣。我没有考虑过使用库。感谢分享。 – vshl
我没有看到它可以在目录中获取图像的代码。我会给你一个代码示例。 –