【发布时间】:2015-11-03 19:46:53
【问题描述】:
我正在尝试解决这个问题。我有一些代码使用 CursorLoader 从 sdcard 中查询图像,并在 SimpleCursorAdapter 的帮助下将它们显示在 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。我试了一下,但我不知道要为此创建什么样的模型。对此的任何帮助表示赞赏。谢谢。
【问题讨论】:
-
这个问题中的代码对我有用,我让它运行是为了回答这个问题(虽然使用了一个库):stackoverflow.com/questions/30407581/…
-
有趣。我没有考虑为此使用库。感谢分享。
-
我没有看到可以在目录中获取图像的代码。我会给你一个代码示例。
标签: android android-fragments android-gridview android-recyclerview android-cursorloader