标签:android style class code java tar
这篇文章将前几篇使用的方法进行了整合,让我们能够在后台线程中加载以及缓存图片并在ViewPager和GridView中展示出来,并在这些过程中处理并发以及参数的设置.
将图片加载到ViewPager中
使用滑动视图来对图片详情进行导航是一种不错的方式.我们可以使用ViewPager和PagerAdapter来实现.但是,使用FragmentStatePagerAdapter可能会更好,它能够自动地保存ViewPager中Fragment的状态并控制它的创建和销毁,能够有效地利用内存.
注意:如果你仅仅需要加载少量的图片,并且能够确认这些图片不会造成内存溢出,则使用普通的PagerAdapter或者FragmenetPagerAdapter可能会更合适.
以下是使用ViewPager实现的图片展示:
- public class ImageDetailActivity extends FragmentActivity {
- public static final String EXTRA_IMAGE = "extra_image";
-
- private ImagePagerAdapter mAdapter;
- private ViewPager mPager;
-
-
- 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);
-
- 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);
- }
- }
- }
public class ImageDetailActivity extends FragmentActivity {
public static final String EXTRA_IMAGE = "extra_image";
private ImagePagerAdapter mAdapter;
private ViewPager mPager;
// 静态的图片资源数组
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); // 布局中仅仅包含一个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);
}
}
}
以下是一个包含了ImageView的Fragment,用于展示图片.这部分代码看起来是一个十分理想的实现,但是你能够看出它的缺点吗?该怎么改进它?
- 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;
- }
-
-
- public ImageDetailFragment() {}
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- mImageNum = getArguments() != null ? getArguments().getInt(IMAGE_DATA_EXTRA) : -1;
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
-
- 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);
- }
- }
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 = getArguments() != 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); // 将图片加载到ImageView中
}
}
从以上代码中,你可能发现了:图片是直接从资源文件中读取并展示到UI上的,这可能会造成应用挂起或者被强制关闭.此处使用AsyncTask在后台线程中加载图片会更好:
- 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);
- }
-
- ...
- }
-
- 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];
-
- ((ImageDetailActivity) getActivity()).loadBitmap(resId, mImageView);
- }
- }
- }
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];
// 在后台线程中加载图片,而不是在Activity中直接读取图片
((ImageDetailActivity) getActivity()).loadBitmap(resId, mImageView);
}
}
}
这样,我们可以在BitmapWorkerTask中实现任何附加的操作(如改变尺寸或者从网络读取图片资源)而不会映像UI线程的响应速度.就算使用后台线程加载图片的效率比直接加载图片低,我们也可以将使用的图片添加到缓存中以便复用.以下是添加缓存的方式:
- public class ImageDetailActivity extends FragmentActivity {
- ...
- private LruCache<String, Bitmap> mMemoryCache;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- ...
-
- }
-
- 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);
- }
- }
-
- ...
- }
public class ImageDetailActivity extends FragmentActivity {
...
private LruCache<String, Bitmap> 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中的实现
网格结构的视图有利于展示多张图片,这种结果可以通过GridView来实现.而GridView可用通过用户的滑动操作及时地将图片显示出来.要实现这种效果,我们必须保证UI线程不被阻塞,内存的使用也要处于控制之中,而且图片的并发加载也要处理好(基于GridView的子View的循环使用).
开始之前,这里有一个使用GridView和Fragment(包含ImageView)的实现:
- public class ImageGridFragment extends Fragment implements AdapterView.OnItemClickListener {
- private ImageAdapter mAdapter;
-
-
- 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};
-
-
-
- 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) {
- 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]);
- return imageView;
- }
- }
- }
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中,子View是可以被复用的.具体处理方式,可以参考Processing
Bitmaps Off the UI Thread.如下是此处的处理:
- 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<BitmapWorkerTask> bitmapWorkerTaskReference;
-
- public AsyncDrawable(Resources res, Bitmap bitmap,
- BitmapWorkerTask bitmapWorkerTask) {
- super(res, bitmap);
- bitmapWorkerTaskReference =
- new WeakReference<BitmapWorkerTask>(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) {
-
- bitmapWorkerTask.cancel(true);
- } else {
-
- return false;
- }
- }
-
- 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;
- }
-
- ...
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<BitmapWorkerTask> bitmapWorkerTaskReference;
public AsyncDrawable(Resources res, Bitmap bitmap,
BitmapWorkerTask bitmapWorkerTask) {
super(res, bitmap);
bitmapWorkerTaskReference =
new WeakReference<BitmapWorkerTask>(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;
}
... // include updated BitmapWorkerTask class
注意:此处的处理同样适用于ListView.
在此处的处理中,我们实现了对图片的灵活加载以及处理,并且保证了UI线程的流畅性.在后台线程中我们能够加载网络图片或者对大图片进行处理.
高效地加载图片(五) 将图片展示在UI中,布布扣,bubuko.com
高效地加载图片(五) 将图片展示在UI中
标签:android style class code java tar
原文地址:http://www.cnblogs.com/chenchong/p/3720854.html