Displaying Bitmaps in Your UI [在UI上呈现Bitmap]

  • 这一课会演示如何运用前面三节课的内容,使用后台线程与Cache机制来加载图片到

​ViewPager​

​GridView​

  • [并发问题的处理确实需要好好考虑,大多数App都没有仔细考虑到这个问题,会导致浪费更多的资源,效率不够]。


Load Bitmaps into a ViewPager Implementation [实现加载图片到ViewPager]


  • ​swipe view pattern​​​ 是一个用来切换显示不同详情界面的很好的方法。[关于这种效果请先参看​​Android Design: Swipe Views​​ ,这是一个很好的设计,在很多App里面都可以看到这种设计,例如网易阅读,在阅读文章时可以左右滑动来切换文章,在Google Reader里面文章的切换也是这样,不过最终网易还是做的稍微好些,因为GReader对手势的判断有点过了,一不小心左右碰到就可能文章被切换掉,这点让我很苦恼,而网易阅读避免了这样的问题,需要用户动作稍大才会出现切换的效果] .
  • 你可以通过​​PagerAdapter​​ 与

​ViewPager​

  • 组件来实现这个效果. 然而,一个更加合适的Adapter是​​PagerAdapter​​ 的子类

​FragmentStatePagerAdapter​​:​

  • 它可以在某个ViewPager中的子视图切换出屏幕时自动销毁与保存

​Fragments​

  • Note:如果你只有为数不多的图片并且确保不会超出程序内存限制,那么使用

​PagerAdapter​

​FragmentPagerAdapter​

  • 会更加合适。
  • 下面是一个使用ViewPager与ImageView作为子视图的示例。

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



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


• 希望你有发现上面示例存在的问题:在UI Thread中读取图片可能会导致程序ANR。使用在Lesson 2中学习的
​​​AsyncTask​​​
• 会比较好。

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


  • 在​​BitmapWorkerTask​​ 中做一些例如resizing or fetching images from the network,不会卡到UI Thread。如果后台线程不仅仅是做个简单的直接加载动作,增加一个内存Cache或者磁盘Cache会比较好[参考Lesson 3]

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




Load Bitmaps into a GridView Implementation [实现加载图片到GridView]



• ​​grid list building block​​ 是一种有效显示大量图片的方式。这样能够一次显示许多图片,而且那些即将被显示的图片也处于准备显示状态。如果你想要实现这种效果,你必须确保UI是流畅的,能够控制内存使用,并且正确的处理并发问题(因为
​​​GridView​​​
• 下面是一个在Fragment里面内置了ImageView作为GridView子视图的示例:


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


1. //请注意下面的代码
2. // Load image into ImageView
3. return imageView;
4. }
5. }



• 与前面加载到图片到ViewPager一样,如果setImageResource的操作会比较耗时,有可能会卡到UI Thread。
• 可以使用类似前面异步处理图片与增加缓存的方法来解决那个问题。然而,我们还需要考虑GridView的循环机制所带来的并发问题。为了处理这个问题,请参考前面Lesson 2:​​Processing Bitmaps Off the UI Thread​​ 。下面是一个更新的解决方案:


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

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



  • 上面的方法提供了足够的弹性,使得你可以做从网络加载与Resize大的数码照片等操作而不至于卡到UI Thread。
  • 对于完整的代码示例,下载链接:http://developer.android.com/shareables/training/BitmapFun.zip