Android教程进阶:在你的UI中显示位图

时间:2013-03-19 09:36来源:eoeAndroid 作者:adminjet 点击:

这一节向你展示通过在后台线程中结合位图缓存如何加载多张位图到ViewPagerGridView组件中,当处理并发性和用户配置变化的时候.

加载位图到一个ViewPager的实现


swipe view pattern是一个很好的方式来浏览图片库的详细视图.你能实现这个模式使用ViewPager组件支持的PagerAdapter.然而,一个更合适的支持适配器是一个子类FragmentStatePagerAdapter,当它们退出屏幕时在ViewPager中它自动销毁和保存Fragments的状态,使得不会太占内存.

注意:如果你只有少量的图片,并且能保证它们是在应用程序内存限制以内,然后使用普通的PagerAdapter或者FragmentPagerAdapter可能更合适.

接下来是一个包含ImageView子视图的ViewPager的实现.主活动中持有ViewPager和相应的适配器:

  public class ImageDetailActivity extends FragmentActivity {

  public static final String EXTRA_IMAGE = “extra_image”;

  private ImagePagerAdapter mAdapter;

  private ViewPager mPager;

  // A static dataset to back the ViewPager adapter

  public final static Integer[] imageResIds = new Integer[] {

  R.drawable.sample_image_1, R.drawable.sample_image_2, R.drawable.sample_image_3,

  R.drawable.sample_image_4, R.drawable.sample_image_5, R.drawable.sample_image_6,

  R.drawable.sample_image_7, R.drawable.sample_image_8, R.drawable.sample_image_9};

  @Override

  public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.image_detail_pager); // Contains just a ViewPager

  mAdapter = new ImagePagerAdapter(getSupportFragmentManager(), imageResIds.length);

  mPager = (ViewPager) findViewById(R.id.pager);

  mPager.setAdapter(mAdapter);

  }

  public static class ImagePagerAdapter extends FragmentStatePagerAdapter {

  private final int mSize;

  public ImagePagerAdapter(FragmentManager fm, int size) {

  super(fm);

  mSize = size;

  }

  @Override

  public int getCount() {

  return mSize;

  }

  @Override

  public Fragment getItem(int position) {

  return ImageDetailFragment.newInstance(position);

  }

  }

  }

这个是Fragment持有ImageView子视图的细节:

  public class ImageDetailFragment extends Fragment {

  private static final String IMAGE_DATA_EXTRA = “resId”;

  private int mImageNum;

  private ImageView mImageView;

  static ImageDetailFragment newInstance(int imageNum) {

  final ImageDetailFragment f = new ImageDetailFragment();

  final Bundle args = new Bundle();

  args.putInt(IMAGE_DATA_EXTRA, imageNum);

  f.setArguments(args);

  return f;

  }

  // Empty constructor, required as per Fragment docs

  public ImageDetailFragment() {}

  @Override

  public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  mImageNum null ? getArguments()。getInt(IMAGE_DATA_EXTRA) : -1;

  }

  @Override

  public View onCreateView(LayoutInflater inflater, ViewGroup container,

  Bundle savedInstanceState) {

  // image_detail_fragment.xml contains just an ImageView

  final View v = inflater.inflate(R.layout.image_detail_fragment, container, false);

  mImageView = (ImageView) v.findViewById(R.id.imageView);

  return v;

  }

  @Override

  public void onActivityCreated(Bundle savedInstanceState) {

  super.onActivityCreated(savedInstanceState);

  final int resId = ImageDetailActivity.imageResIds[mImageNum];

  mImageView.setImageResource(resId); // Load image into ImageView

  }

  }
希望你注意到这个实现的问题;在UI线程中从资源文件中读取文件的话,会导致应用程序悬挂和被强制关闭.使用一个AsyncTaskProcessing Bitmaps Off the UI Thread一节中已经描述了,在将图片的加载和处理移交给后台线程这是最直接的方式了:
  public class ImageDetailActivity extends FragmentActivity {

  …

  public void loadBitmap(int resId, ImageView imageView) {

  mImageView.setImageResource(R.drawable.image_placeholder);

  BitmapWorkerTask task = new BitmapWorkerTask(mImageView);

  task.execute(resId);

  }

  … // include BitmapWorkerTask class

  }

  public class ImageDetailFragment extends Fragment {

  …

  @Override

  public void onActivityCreated(Bundle savedInstanceState) {

  super.onActivityCreated(savedInstanceState);

  if (ImageDetailActivity.class.isInstance(getActivity())) {

  final int resId = ImageDetailActivity.imageResIds[mImageNum];

  // Call out to ImageDetailActivity to load the bitmap in a background thread

  ((ImageDetailActivity) getActivity())。loadBitmap(resId, mImageView);

  }

  }

  }
任何额外的处理(如调整大小或从网络获取图像),在不影响主UI的响应情况下,可以在BitmapWorkerTask 中操作.如果后台线程所做的不仅仅是直接从磁盘加载图像,那么在Caching Bitmaps一节中阐述了添加一个内存或者磁盘的缓存也同样可以.接下来是针对一个内存缓存的额外的修改:
  public class ImageDetailActivity extends FragmentActivity {

  …

  private LruCache mMemoryCache;

  @Override

  public void onCreate(Bundle savedInstanceState) {

  …

  // initialize LruCache as per Use a Memory Cache section

  }

  public void loadBitmap(int resId, ImageView imageView) {

  final String imageKey = String.valueOf(resId);

  final Bitmap bitmap = mMemoryCache.get(imageKey);

  if (bitmap != null) {

  mImageView.setImageBitmap(bitmap);

  } else {

  mImageView.setImageResource(R.drawable.image_placeholder);

  BitmapWorkerTask task = new BitmapWorkerTask(mImageView);

  task.execute(resId);

  }

  }

  … // include updated BitmapWorkerTask from Use a Memory Cache section

  }
把所有的知识点整合在一起,给你一个响应ViewPager的实现,在你的图片需要加载的时候,用最小的图片加载延迟和尽可能多或少的后台处理.

加载位图到GridView视图的实现


grid list building block是用于显示图像的数据集,并可以实现使用一个GridView组件,如果用户向上或向下滚动的话,其中许多屏幕上的图像可以在任何时候以及更多时候需要随时可以出现。在实施这种类型的控制,你必须确保UI保持流畅,内存使用情况仍然在可控制的情况下,并发地正确处理由于GridView的循环利用子控件的情况. 首先,这里是一个标准的GridView控件实现ImageView子控件放在GridView里的一个Fragment:


  public class ImageGridFragment extends Fragment implements AdapterView.OnItemClickListener {

  private ImageAdapter mAdapter;

  // A static dataset to back the GridView adapter

  public final static Integer[] imageResIds = new Integer[] {

  R.drawable.sample_image_1, R.drawable.sample_image_2, R.drawable.sample_image_3,

  R.drawable.sample_image_4, R.drawable.sample_image_5, R.drawable.sample_image_6,

  R.drawable.sample_image_7, R.drawable.sample_image_8, R.drawable.sample_image_9};

  // Empty constructor as per Fragment docs

  public ImageGridFragment() {}

  @Override

  public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  mAdapter = new ImageAdapter(getActivity());

  }

  @Override

  public View onCreateView(

  LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

  final View v = inflater.inflate(R.layout.image_grid_fragment, container, false);

  final GridView mGridView = (GridView) v.findViewById(R.id.gridView);

  mGridView.setAdapter(mAdapter);

  mGridView.setOnItemClickListener(this);

  return v;

  }

  @Override

  public void onItemClick(AdapterView parent, View v, int position, long id) {

  final Intent i = new Intent(getActivity(), ImageDetailActivity.class);

  i.putExtra(ImageDetailActivity.EXTRA_IMAGE, position);

  startActivity(i);

  }

  private class ImageAdapter extends BaseAdapter {

  private final Context mContext;

  public ImageAdapter(Context context) {

  super();

  mContext = context;

  }

  @Override

  public int getCount() {

  return imageResIds.length;

  }

  @Override

  public Object getItem(int position) {

  return imageResIds[position];

  }

  @Override

  public long getItemId(int position) {

  return position;

  }

  @Override

  public View getView(int position, View convertView, ViewGroup container) {

  ImageView imageView;

  if (convertView == null) { // if it's not recycled, initialize some attributes

  imageView = new ImageView(mContext);

  imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

  imageView.setLayoutParams(new GridView.LayoutParams(

  LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

  } else {

  imageView = (ImageView) convertView;

  }

  imageView.setImageResource(imageResIds[position]); // Load image into ImageView

  return imageView;

  }

  }

  }

再一次,与此相关的问题是,执行的映像将被设置在UI线程。然而这可能只适合于小的,简单的图片(由于 系统资源加载和缓存),如果需要做任何额外的处理,你的UI不再响应。 同一个异步处理和超速缓存方法从上一节可以在此实施。 但是,您还需要警惕的并发问题,GridView回收其 子视图。要解决这个问题,请使用在处理位图关闭 UI 线程课中讨论的技术。这里是已更新的解决方案:


  public class ImageGridFragment extends Fragment implements AdapterView.OnItemClickListener {

  …

  private class ImageAdapter extends BaseAdapter {

  …

  @Override

  public View getView(int position, View convertView, ViewGroup container) {

  …

  loadBitmap(imageResIds[position], imageView)

  return imageView;

  }

  }

  public void loadBitmap(int resId, ImageView imageView) {

  if (cancelPotentialWork(resId, imageView)) {

  final BitmapWorkerTask task = new BitmapWorkerTask(imageView);

  final AsyncDrawable asyncDrawable =

  new AsyncDrawable(getResources(), mPlaceHolderBitmap, task);

  imageView.setImageDrawable(asyncDrawable);

  task.execute(resId);

  }

  }

  static class AsyncDrawable extends BitmapDrawable {

  private final WeakReference bitmapWorkerTaskReference;

  public AsyncDrawable(Resources res, Bitmap bitmap,

  BitmapWorkerTask bitmapWorkerTask) {

  super(res, bitmap);

  bitmapWorkerTaskReference =

  new WeakReference(bitmapWorkerTask);

  }

  public BitmapWorkerTask getBitmapWorkerTask() {

  return bitmapWorkerTaskReference.get();

  }

  }

  public static boolean cancelPotentialWork(int data, ImageView imageView) {

  final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);

  if (bitmapWorkerTask != null) {

  final int bitmapData = bitmapWorkerTask.data;

  if (bitmapData != data) {

  // Cancel previous task

  bitmapWorkerTask.cancel(true);

  } else {

  // The same work is already in progress

  return false;

  }

  }

  // No task associated with the ImageView, or an existing task was cancelled

  return true;

  }

  private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {

  if (imageView != null) {

  final Drawable drawable = imageView.getDrawable();

  if (drawable instanceof AsyncDrawable) {

  final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;

  return asyncDrawable.getBitmapWorkerTask();

  }

  }

  return null;

  }

注意:这些相同的代码对ListView组件来说也很适合.

这种实现在不妨碍UI的平滑度的情况下能灵活地处理和加载图片.在后台任务中,你可以加载从网络下载的图片或者调整大数码相机拍摄的照片,并且一旦任务完成后图片立刻显示.

分享到:

凌阳教育安卓培训【凌阳科技旗下教育品牌】——专业的安卓培训机构,全国唯一“按班公布学员就业去向”的诚信机构

关注我们:

全国免费咨询电话:156-0117-5697 服务监督电话:010-62981113-2800

京ICP备09010168号  京公网安备11010802010586号

北京安卓培训中心:海淀区上地信息产业基地中黎科技园1号楼3层A段

Copyright © 2016 SunplusEdu Inc. All Rights Reserved