在UI上显示Bitmap

编写:kesenhoo - 原文:http://developer.android.com/training/displaying-bitmaps/display-bitmap.html

这一课会演示如何运用前面几节课的内容,使用后台线程与缓存机制将图片加载到ViewPager与GridView控件,并且学习处理并发与配置改变问题。

实现加载图片到ViewPager

Swipe View Pattern是一个使用滑动来切换显示不同详情页面的设计模型。(关于这种效果请先参看Android Design: Swipe Views)。我们可以通过PagerAdapterViewPager控件来实现这个效果。 不过,一个更加合适的Adapter是PagerAdapter的一个子类,叫做FragmentStatePagerAdapter:它可以在某个ViewPager中的子视图切换出屏幕时自动销毁与保存Fragments的状态。这样能够保持更少的内存消耗。

Note: 如果只有为数不多的图片并且确保不会超出程序内存限制,那么使用PagerAdapter或 FragmentPagerAdapter会更加合适。

下面是一个使用ViewPager与ImageView作为子视图的示例。主Activity包含有ViewPager和Adapter。

  1. public class ImageDetailActivity extends FragmentActivity {
  2. public static final String EXTRA_IMAGE = "extra_image";
  3. private ImagePagerAdapter mAdapter;
  4. private ViewPager mPager;
  5. // A static dataset to back the ViewPager adapter
  6. public final static Integer[] imageResIds = new Integer[] {
  7. R.drawable.sample_image_1, R.drawable.sample_image_2, R.drawable.sample_image_3,
  8. R.drawable.sample_image_4, R.drawable.sample_image_5, R.drawable.sample_image_6,
  9. R.drawable.sample_image_7, R.drawable.sample_image_8, R.drawable.sample_image_9};
  10. @Override
  11. public void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. setContentView(R.layout.image_detail_pager); // Contains just a ViewPager
  14. mAdapter = new ImagePagerAdapter(getSupportFragmentManager(), imageResIds.length);
  15. mPager = (ViewPager) findViewById(R.id.pager);
  16. mPager.setAdapter(mAdapter);
  17. }
  18. public static class ImagePagerAdapter extends FragmentStatePagerAdapter {
  19. private final int mSize;
  20. public ImagePagerAdapter(FragmentManager fm, int size) {
  21. super(fm);
  22. mSize = size;
  23. }
  24. @Override
  25. public int getCount() {
  26. return mSize;
  27. }
  28. @Override
  29. public Fragment getItem(int position) {
  30. return ImageDetailFragment.newInstance(position);
  31. }
  32. }
  33. }

Fragment里面包含了ImageView控件:

  1. public class ImageDetailFragment extends Fragment {
  2. private static final String IMAGE_DATA_EXTRA = "resId";
  3. private int mImageNum;
  4. private ImageView mImageView;
  5. static ImageDetailFragment newInstance(int imageNum) {
  6. final ImageDetailFragment f = new ImageDetailFragment();
  7. final Bundle args = new Bundle();
  8. args.putInt(IMAGE_DATA_EXTRA, imageNum);
  9. f.setArguments(args);
  10. return f;
  11. }
  12. // Empty constructor, required as per Fragment docs
  13. public ImageDetailFragment() {}
  14. @Override
  15. public void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. mImageNum = getArguments() != null ? getArguments().getInt(IMAGE_DATA_EXTRA) : -1;
  18. }
  19. @Override
  20. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  21. Bundle savedInstanceState) {
  22. // image_detail_fragment.xml contains just an ImageView
  23. final View v = inflater.inflate(R.layout.image_detail_fragment, container, false);
  24. mImageView = (ImageView) v.findViewById(R.id.imageView);
  25. return v;
  26. }
  27. @Override
  28. public void onActivityCreated(Bundle savedInstanceState) {
  29. super.onActivityCreated(savedInstanceState);
  30. final int resId = ImageDetailActivity.imageResIds[mImageNum];
  31. mImageView.setImageResource(resId); // Load image into ImageView
  32. }
  33. }

希望你有发现上面示例存在的问题:在UI线程中读取图片可能会导致应用无响应。因此使用在第二课中学习的AsyncTask会更好。

  1. public class ImageDetailActivity extends FragmentActivity {
  2. ...
  3. public void loadBitmap(int resId, ImageView imageView) {
  4. mImageView.setImageResource(R.drawable.image_placeholder);
  5. BitmapWorkerTask task = new BitmapWorkerTask(mImageView);
  6. task.execute(resId);
  7. }
  8. ... // include BitmapWorkerTask class
  9. }
  10. public class ImageDetailFragment extends Fragment {
  11. ...
  12. @Override
  13. public void onActivityCreated(Bundle savedInstanceState) {
  14. super.onActivityCreated(savedInstanceState);
  15. if (ImageDetailActivity.class.isInstance(getActivity())) {
  16. final int resId = ImageDetailActivity.imageResIds[mImageNum];
  17. // Call out to ImageDetailActivity to load the bitmap in a background thread
  18. ((ImageDetailActivity) getActivity()).loadBitmap(resId, mImageView);
  19. }
  20. }
  21. }

在BitmapWorkerTask中做一些例如重设图片大小,从网络拉取图片的任务,可以确保不会阻塞UI线程。如果后台线程不仅仅是一个简单的加载操作,增加一个内存缓存或者磁盘缓存会比较好(请参考第三课:缓存Bitmap),下面是一些为了内存缓存而附加的内容:

  1. public class ImageDetailActivity extends FragmentActivity {
  2. ...
  3. private LruCache mMemoryCache;
  4. @Override
  5. public void onCreate(Bundle savedInstanceState) {
  6. ...
  7. // initialize LruCache as per Use a Memory Cache section
  8. }
  9. public void loadBitmap(int resId, ImageView imageView) {
  10. final String imageKey = String.valueOf(resId);
  11. final Bitmap bitmap = mMemoryCache.get(imageKey);
  12. if (bitmap != null) {
  13. mImageView.setImageBitmap(bitmap);
  14. } else {
  15. mImageView.setImageResource(R.drawable.image_placeholder);
  16. BitmapWorkerTask task = new BitmapWorkerTask(mImageView);
  17. task.execute(resId);
  18. }
  19. }
  20. ... // include updated BitmapWorkerTask from Use a Memory Cache section
  21. }

把前面学习到的所有技巧合并起来,我们将得到一个响应性良好的ViewPager实现:它拥有最小的加载延迟,同时可以根据实际需求执行不同的后台处理任务。

实现加载图片到GridView

Grid List Building Block是一种有效显示大量图片的方式。它能够一次显示许多图片,同时即将被显示的图片会处于准备显示的状态。如果我们想要实现这种效果,必须确保UI是流畅的,能够控制内存使用,并且正确处理并发问题(因为GridView会循环使用子视图)。

下面是一个典型的使用场景,在Fragment里面内置GridView,其中GridView的子视图是ImageView:

  1. public class ImageGridFragment extends Fragment implements AdapterView.OnItemClickListener {
  2. private ImageAdapter mAdapter;
  3. // A static dataset to back the GridView adapter
  4. public final static Integer[] imageResIds = new Integer[] {
  5. R.drawable.sample_image_1, R.drawable.sample_image_2, R.drawable.sample_image_3,
  6. R.drawable.sample_image_4, R.drawable.sample_image_5, R.drawable.sample_image_6,
  7. R.drawable.sample_image_7, R.drawable.sample_image_8, R.drawable.sample_image_9};
  8. // Empty constructor as per Fragment docs
  9. public ImageGridFragment() {}
  10. @Override
  11. public void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. mAdapter = new ImageAdapter(getActivity());
  14. }
  15. @Override
  16. public View onCreateView(
  17. LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  18. final View v = inflater.inflate(R.layout.image_grid_fragment, container, false);
  19. final GridView mGridView = (GridView) v.findViewById(R.id.gridView);
  20. mGridView.setAdapter(mAdapter);
  21. mGridView.setOnItemClickListener(this);
  22. return v;
  23. }
  24. @Override
  25. public void onItemClick(AdapterView parent, View v, int position, long id) {
  26. final Intent i = new Intent(getActivity(), ImageDetailActivity.class);
  27. i.putExtra(ImageDetailActivity.EXTRA_IMAGE, position);
  28. startActivity(i);
  29. }
  30. private class ImageAdapter extends BaseAdapter {
  31. private final Context mContext;
  32. public ImageAdapter(Context context) {
  33. super();
  34. mContext = context;
  35. }
  36. @Override
  37. public int getCount() {
  38. return imageResIds.length;
  39. }
  40. @Override
  41. public Object getItem(int position) {
  42. return imageResIds[position];
  43. }
  44. @Override
  45. public long getItemId(int position) {
  46. return position;
  47. }
  48. @Override
  49. public View getView(int position, View convertView, ViewGroup container) {
  50. ImageView imageView;
  51. if (convertView == null) { // if it's not recycled, initialize some attributes
  52. imageView = new ImageView(mContext);
  53. imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
  54. imageView.setLayoutParams(new GridView.LayoutParams(
  55. LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
  56. } else {
  57. imageView = (ImageView) convertView;
  58. }
  59. //请注意下面的代码
  60. imageView.setImageResource(imageResIds[position]); // Load image into ImageView
  61. return imageView;
  62. }
  63. }

这里同样有一个问题,上面的代码实现中,犯了把图片加载放在UI线程进行处理的错误。如果只是加载一些很小的图片,或者是经过Android系统缩放并缓存过的图片,上面的代码在运行时不会有太大问题,但是如果加载的图片稍微复杂耗时一点,这都会导致你的UI卡顿甚至应用无响应。

与前面加载图片到ViewPager一样,如果setImageResource的操作会比较耗时,也有可能会阻塞UI线程。不过我们可以使用类似前面异步处理图片与增加缓存的方法来解决这个问题。然而,我们还需要考虑GridView的循环机制所带来的并发问题。为了处理这个问题,可以参考前面的课程 。下面是一个更新过后的解决方案:

  1. public class ImageGridFragment extends Fragment implements AdapterView.OnItemClickListener {
  2. ...
  3. private class ImageAdapter extends BaseAdapter {
  4. ...
  5. @Override
  6. public View getView(int position, View convertView, ViewGroup container) {
  7. ...
  8. loadBitmap(imageResIds[position], imageView)
  9. return imageView;
  10. }
  11. }
  12. public void loadBitmap(int resId, ImageView imageView) {
  13. if (cancelPotentialWork(resId, imageView)) {
  14. final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
  15. final AsyncDrawable asyncDrawable =
  16. new AsyncDrawable(getResources(), mPlaceHolderBitmap, task);
  17. imageView.setImageDrawable(asyncDrawable);
  18. task.execute(resId);
  19. }
  20. }
  21. static class AsyncDrawable extends BitmapDrawable {
  22. private final WeakReference bitmapWorkerTaskReference;
  23. public AsyncDrawable(Resources res, Bitmap bitmap,
  24. BitmapWorkerTask bitmapWorkerTask) {
  25. super(res, bitmap);
  26. bitmapWorkerTaskReference =
  27. new WeakReference(bitmapWorkerTask);
  28. }
  29. public BitmapWorkerTask getBitmapWorkerTask() {
  30. return bitmapWorkerTaskReference.get();
  31. }
  32. }
  33. public static boolean cancelPotentialWork(int data, ImageView imageView) {
  34. final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
  35. if (bitmapWorkerTask != null) {
  36. final int bitmapData = bitmapWorkerTask.data;
  37. if (bitmapData != data) {
  38. // Cancel previous task
  39. bitmapWorkerTask.cancel(true);
  40. } else {
  41. // The same work is already in progress
  42. return false;
  43. }
  44. }
  45. // No task associated with the ImageView, or an existing task was cancelled
  46. return true;
  47. }
  48. private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
  49. if (imageView != null) {
  50. final Drawable drawable = imageView.getDrawable();
  51. if (drawable instanceof AsyncDrawable) {
  52. final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
  53. return asyncDrawable.getBitmapWorkerTask();
  54. }
  55. }
  56. return null;
  57. }
  58. ... // include updated BitmapWorkerTask class

Note:对于ListView同样可以套用上面的方法。

上面的方法提供了足够的弹性,使得我们可以做从网络下载图片,并对大尺寸大的数码照片做缩放等操作而不至于阻塞UI线程。