@flyouting
2014-03-19T06:58:40.000000Z
字数 2345
阅读 3780
这是基于Android Studio及Fragment的相机开发的第二章,如果你还没准备好,先去github上拉一下我的一个示例工程。本章主要包含“SimplePhotoGalleryListFragment.”
把我们所有的图片加载到Android Studio的一个list里是一项繁杂的任务。因此,我们需要使用一个在Android体系中被称为AsyncTaskLoader的类,在这个例子里,我专门写了一个自定义的AsyncTaskLoader。通过PhotoGalleryImageProvider这个工具类调用去加载相册图片。
Fragments 中提供一个特别的接口去启动async task loaders并与其交互。在我们的文件中如此:
@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);// Create an empty loader and pre-initialize the photo list items as an empty list.Context context = getActivity().getBaseContext();// Set up empty mAdaptermPhotoListItem = new ArrayList() ;mAdapter = new PhotoAdapter(context, R.layout.photo_item, mPhotoListItem, false);// Prepare the loader. Either re-connect with an existing one,// or start a new one.getLoaderManager().initLoader(0, null, this); }}
注意最后这行代码,“getLoaderManager().initLoader(0, null, this);”这会自动启动指定的AsyncLoader:
/*** Loader Handlers for loading the photos in the background.*/@Overridepublic Loader<List> onCreateLoader(int id, Bundle args) {// This is called when a new Loader needs to be created. This// sample only has one Loader with no arguments, so it is simple.return new PhotoGalleryAsyncLoader(getActivity());}
Once the background task has finished gathering the gallery images, it returns in this method:
当后台任务执行完,获取到了相册图片时,会回调这个方法:
@Overridepublic void onLoadFinished(Loader<List> loader, List data) {// Set the new data in the mAdapter.mPhotoListItem.clear();for (int i = 0; i < data.size(); i++) {PhotoItem item = data.get(i);mPhotoListItem.add(item);}mAdapter.notifyDataSetChanged();resolveEmptyText();cancelProgressDialog();}
PhotoItems这个模型类包括了图片的缩略图和原始图的url,当这些数据获取后,可以执行notifyDataSetChanged()去加载图片了。
我之前提到过,我提供了一个工具类PhotoGalleryImageProvider用以获取相册中图片的缩略图的cursor。方法如下:
/*** Fetch both full sized images and thumbnails via a single query. Returns* all images not in the Camera Roll.** @param context* @return*/public static List getAlbumThumbnails(Context context){final String[] projection = {MediaStore.Images.Thumbnails.DATA,MediaStore.Images.Thumbnails.IMAGE_ID};Cursor thumbnailsCursor = context.getContentResolver().query( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,projection, // Which columns to returnnull, // Return all rowsnull,null);...return result;}
Android中的Cursors是后台获取图片的一般方法,更高级的使用时CursorLoader。其内置有AsyncTaskLoader,用于自动处理负载转移到后台。可能我通过AsyncTask和CursorLoader也能获取同样的结果,但是我想在列表中渲染获得的图片的缩略图和原始图,所以我使用自定义的 task loader。
详细请查看项目中代码。
翻译:@flyouting
时间:2014/03/19
源地址