【Android】加载网络图片-------转自1

本文介绍了一个Gallery组件的图片懒加载实现方案。该方案通过监听Gallery的滑动状态,在停止滑动时加载当前页面图片,避免了滑动时加载图片导致的卡顿。

转自:http://www.apkbus.com/android-51646-1-1.html

之前在网上找了很多都没有这方面的资料,大概的效果是当Gallery滑动时不下载图片,当Gallery滑动停止时加载当前页面图片,自己花了一点时间大概的实现了,如果各位有更好的意见欢迎说出来大家一起学习。

先上图看看效果:

这图是在加载图片时显示的默认图片,当图片加载完成则替换。



未命名.jpg 
图片加载完成效果图
未命名.jpg



  1. import java.util.ArrayList;

  2. import java.util.HashMap;

  3. import java.util.List;

  4. import android.app.Activity;

  5. import android.graphics.Bitmap;

  6. import android.graphics.BitmapFactory;

  7. import android.os.AsyncTask;

  8. import android.os.Bundle;

  9. import android.os.Handler;

  10. import android.os.Message;

  11. import android.util.Log;

  12. import android.view.KeyEvent;

  13. import android.view.View;

  14. import android.widget.AdapterView;

  15. import android.widget.AdapterView.OnItemClickListener;

  16. import android.widget.AdapterView.OnItemSelectedListener;

  17. import android.widget.Gallery;

  18. public class MyActivity extends Activity implements OnItemClickListener{

  19. public static HashMap<String,Bitmap> imagesCache=new HashMap<String, Bitmap>(); //图片缓存

  20. private Gallery images_ga;

  21. public static ImageAdapter imageAdapter;

  22. private int num=0;

  23. List<String> urls = new ArrayList<String>(); //所有图片地址List

  24. List<String> url = new ArrayList<String>(); //需要下载图片的url地址


  25. @Override

  26. protected void onCreate(Bundle savedInstanceState) {


  27. super.onCreate(savedInstanceState);

  28. setContentView(R.layout.gallery_1);

  29. Files.mkdir(this);

  30. init();

  31. }

  32. private void init(){

  33. Bitmap image= BitmapFactory.decodeResource(getResources(),R.drawable.default_movie_post);

  34. imagesCache.put("background_non_load",image); //设置缓存中默认的图片

  35. images_ga = (Gallery) findViewById(R.id.gallery);

  36. urls.add("http://hiphotos.baidu.com/baidu/pic/item/f603918fa0ec08fabf7a641659ee3d6d55fbda0d.jpg");

  37. urls.add("http://hiphotos.baidu.com/baidu/pic/item/43a7d933c895d143d011bf9273f082025aaf071f.jpg");

  38. urls.add("http://hiphotos.baidu.com/baidu/pic/item/63d0f703918fa0ec2ebf584b269759ee3d6ddb7f.jpg");

  39. urls.add("http://hiphotos.baidu.com/baidu/pic/item/5ab5c9ea15ce36d31ed8387f3af33a87e850b1a5.jpg");

  40. urls.add("http://hiphotos.baidu.com/baidu/pic/item/8601a18b87d6277f6e46217628381f30e924fc2c.jpg");

  41. urls.add("http://hiphotos.baidu.com/baidu/pic/item/b48f8c54acf9964c3a29350e.jpg");

  42. urls.add("http://hiphotos.baidu.com/baidu/pic/item/bd3eb13533fa828b48da6aabfd1f4134960a5af9.jpg");

  43. urls.add("http://hiphotos.baidu.com/baidu/pic/item/29381f30e924b899da3ce5706e061d950a7bf672.jpg");

  44. urls.add("http://hiphotos.baidu.com/baidu/pic/item/bd3eb13533fa828b48da6aabfd1f4134960a5af9.jpg");

  45. urls.add("http://hiphotos.baidu.com/baidu/pic/item/4bed2e738bd4b31cd73d63fd87d6277f9e2ff877.jpg");

  46. urls.add("http://hiphotos.baidu.com/baidu/pic/item/caef76094b36acaf92b619b87cd98d1001e99c24.jpg");

  47. urls.add("http://hiphotos.baidu.com/baidu/pic/item/8435e5dde71190efd6154d95ce1b9d16fcfa608a.jpg");

  48. urls.add("http://hiphotos.baidu.com/baidu/pic/item/b3de9c824ba1d4cd6d81190f.jpg");

  49. urls.add("http://hiphotos.baidu.com/baidu/pic/item/e0fe9925cc2c683834a80f11.jpg");

  50. urls.add("http://hiphotos.baidu.com/baidu/pic/item/0bd162d9f2d3572c65911a988a13632762d0c307.jpg");

  51. urls.add("http://hiphotos.baidu.com/baidu/pic/item/ac6eddc451da81cb2ac1708a5266d01609243155.jpg");


  52. urls.add("http://hiphotos.baidu.com/baidu/pic/item/1bd5ad6e8416d98080cb4a48.jpg");

  53. urls.add("http://hiphotos.baidu.com/baidu/pic/item/3c6d55fbb2fb43169d0508ca20a4462309f7d36c.jpg");

  54. urls.add("http://hiphotos.baidu.com/baidu/pic/item/faedab64034f78f0daf3664a79310a55b2191c8a.jpg");

  55. urls.add("http://hiphotos.baidu.com/baidu/pic/item/2fdda3cc7cd98d10b05af088213fb80e7aec90f9.jpg");

  56. urls.add("http://hiphotos.baidu.com/baidu/pic/item/b8014a90f603738d9536f39bb31bb051f819ec0f.jpg");

  57. urls.add("http://hiphotos.baidu.com/baidu/pic/item/2fdda3cc7cd98d10b05af088213fb80e7aec90f9.jpg");

  58. imageAdapter = new ImageAdapter(urls, this);

  59. images_ga.setAdapter(imageAdapter);

  60. images_ga.setOnItemClickListener(this);

  61. images_ga.setOnItemSelectedListener(new OnItemSelectedListener() {

  62. @Override

  63. public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

  64. num=arg2;

  65. Log.i("mahua", "ItemSelected=="+arg2);

  66. GalleryWhetherStop();

  67. }

  68. @Override

  69. public void onNothingSelected(AdapterView<?> arg0) {

  70. // TODO Auto-generated method stub


  71. }

  72. });

  73. }



  74. @Override

  75. public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

  76. Log.i("GOLF", "第"+arg2+"个被点击了");

  77. }


  78. /**

  79. * 判断Gallery滚动是否停止,如果停止则加载当前页面的图片

  80. */

  81. private void GalleryWhetherStop() {

  82. Runnable runnable = new Runnable() {

  83. public void run() {

  84. try {

  85. int index =0;

  86. index = num;

  87. Thread.sleep(1000);

  88. if (index == num) {

  89. url.add(urls.get(num));

  90. if(num!=0 && urls.get(num-1)!=null) {

  91. url.add(urls.get(num-1));

  92. }

  93. if(num!=urls.size()-1 && urls.get(num+1)!=null) {

  94. url.add(urls.get(num+1));

  95. }

  96. Message m = new Message();

  97. m.what = 1;

  98. mHandler.sendMessage(m);

  99. }

  100. } catch (Exception e) {

  101. e.printStackTrace();

  102. }

  103. }

  104. };

  105. new Thread(runnable).start();

  106. }



  107. // 加载图片的异步任务

  108. class LoadImageTask extends AsyncTask<String, Void, Bitmap> {

  109. @Override 
  110. protected void onCancelled() { 
  111. // TODO Auto-generated method stub 
  112. super.onCancelled(); 

  113. @Override 
  114. protected void onPostExecute(Bitmap result) { 
  115. // TODO Auto-generated method stub 
  116. super.onPostExecute(result); 


  117. @Override

  118. protected Bitmap doInBackground(String... params) {

  119. Bitmap bitmap = null;

  120. try {

  121. String url = params[0];

  122. boolean isExists = Files.compare(url); //这里是自己写的工具类,判断本地缓存是否已经下载过图片

  123. if (isExists == false) {//如果不存在就去下载图片

  124. Net net = new Net();

  125. byte[] data = net.downloadResource(MyActivity.this, url);

  126. bitmap = BitmapFactory

  127. .decodeByteArray(data, 0, data.length);

  128. imagesCache.put(url, bitmap); // 把下载好的图片保存到缓存中

  129. Files.saveImage(url, data);

  130. } else {//如果存在直接读取缓存图片

  131. byte[] data = Files.readImage(url);

  132. bitmap = BitmapFactory

  133. .decodeByteArray(data, 0, data.length);

  134. imagesCache.put(url, bitmap); // 把下载好的图片保存到缓存中

  135. }

  136. Message m = new Message();//图片加载完成通知重新加载

  137. m.what = 0;

  138. mHandler.sendMessage(m);

  139. } catch (Exception e) {

  140. e.printStackTrace();

  141. }

  142. return bitmap;

  143. }


  144. }



  145. private Handler mHandler = new Handler() {

  146. public void handleMessage(Message msg) {

  147. try {

  148. switch (msg.what) {

  149. case 0: {

  150. imageAdapter.notifyDataSetChanged();

  151. break;

  152. }

  153. case 1: {

  154. for(int i=0; i<url.size(); i++) {

  155. LoadImageTask task = new LoadImageTask();//异步加载图片

  156. task.execute(url.get(i));

  157. Log.i("mahua", url.get(i));

  158. }

  159. url.clear();

  160. }

  161. }

  162. super.handleMessage(msg);

  163. } catch (Exception e) {

  164. e.printStackTrace();

  165. }

  166. }

  167. };

  168. @Override

  169. public boolean onKeyDown(int keyCode, KeyEvent event) {

  170. if(keyCode==KeyEvent.KEYCODE_BACK){

  171. System.exit(0);

  172. }

  173. return super.onKeyDown(keyCode, event);

  174. }

  175. }
复制代码
  1. import java.util.List;

  2. import android.content.Context;

  3. import android.content.res.AssetManager;

  4. import android.content.res.TypedArray;

  5. import android.graphics.Bitmap;

  6. import android.view.View;

  7. import android.view.ViewGroup;

  8. import android.widget.BaseAdapter;

  9. import android.widget.Gallery;

  10. import android.widget.ImageView;


  11. public class ImageAdapter extends BaseAdapter {

  12. public static final BaseAdapter Adapter = null;

  13. private List<String> imageUrls; // 图片地址list

  14. private Context context;

  15. int mGalleryItemBackground;


  16. public ImageAdapter(List<String> imageUrls, Context context) {

  17. this.imageUrls = imageUrls;

  18. this.context = context;

  19. // /*

  20. // * 使用在res/values/attrs.xml中的<declare-styleable>定义 的Gallery属性.

  21. // */

  22. TypedArray a = context.obtainStyledAttributes(R.styleable.Gallery1);

  23. /* 取得Gallery属性的Index id */

  24. mGalleryItemBackground = a.getResourceId(

  25. R.styleable.Gallery1_android_galleryItemBackground, 0);

  26. /* 让对象的styleable属性能够反复使用 */

  27. a.recycle();

  28. }

  29. public int getCount() {

  30. return imageUrls.size();

  31. }

  32. public Object getItem(int position) {

  33. return imageUrls.get(position);

  34. }

  35. public long getItemId(int position) {

  36. return position;

  37. }

  38. public View getView(int position, View convertView, ViewGroup parent) {

  39. Bitmap image;

  40. ImageView view = new ImageView(context);

  41. image = MyActivity.imagesCache.get(imageUrls.get(position));

  42. // 从缓存中读取图片

  43. if (image == null) {

  44. image = MyActivity.imagesCache.get("background_non_load");

  45. }

  46. // 设置所有图片的资源地址

  47. view.setImageBitmap(image);

  48. view.setScaleType(ImageView.ScaleType.FIT_XY);

  49. view.setLayoutParams(new Gallery.LayoutParams(240, 320));

  50. view.setBackgroundResource(mGalleryItemBackground);

  51. /* 设置Gallery背景图 */

  52. return view;

  53. }

  54. }
复制代码
attrs.xml
  1. <?xml version="1.0" encoding="utf-8"?>

  2. <resources>

  3. <declare-styleable name="TogglePrefAttrs">

  4. <attr name="android:preferenceLayoutChild" />

  5. </declare-styleable>


  6. <!-- These are the attributes that we want to retrieve from the theme

  7. in view/Gallery1.java -->

  8. <declare-styleable name="Gallery1">

  9. <attr name="android:galleryItemBackground" />

  10. </declare-styleable>


  11. <declare-styleable name="LabelView">

  12. <attr name="text" format="string" />

  13. <attr name="textColor" format="color" />

  14. <attr name="textSize" format="dimension" />

  15. </declare-styleable>

  16. </resources>
复制代码
主要的结构就这样了,下载文件和文件保存自己随便写写就行了。如有更好的建议欢迎提出了,大家一起分享学习。

最后应要求附上源码。
  GallerySync.rar (172.86 KB, 下载次数: 391) 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值