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

图片加载完成效果图

  1. import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import android.app.Activity;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.view.KeyEvent;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.AdapterView.OnItemSelectedListener;
    import android.widget.Gallery;
    public class MyActivity extends Activity implements OnItemClickListener{public static HashMap<String,Bitmap> imagesCache=new HashMap<String, Bitmap>(); //图片缓存private Gallery images_ga;public static ImageAdapter imageAdapter;private int num=0;List<String> urls = new ArrayList<String>(); //所有图片地址ListList<String> url = new ArrayList<String>(); //需要下载图片的url地址@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.gallery_1);Files.mkdir(this);init();}private void init(){Bitmap image= BitmapFactory.decodeResource(getResources(),R.drawable.default_movie_post);imagesCache.put("background_non_load",image);       //设置缓存中默认的图片images_ga = (Gallery) findViewById(R.id.gallery);urls.add("http://hiphotos.baidu.com/baidu/pic/item/f603918fa0ec08fabf7a641659ee3d6d55fbda0d.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/43a7d933c895d143d011bf9273f082025aaf071f.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/63d0f703918fa0ec2ebf584b269759ee3d6ddb7f.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/5ab5c9ea15ce36d31ed8387f3af33a87e850b1a5.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/8601a18b87d6277f6e46217628381f30e924fc2c.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/b48f8c54acf9964c3a29350e.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/bd3eb13533fa828b48da6aabfd1f4134960a5af9.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/29381f30e924b899da3ce5706e061d950a7bf672.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/bd3eb13533fa828b48da6aabfd1f4134960a5af9.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/4bed2e738bd4b31cd73d63fd87d6277f9e2ff877.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/caef76094b36acaf92b619b87cd98d1001e99c24.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/8435e5dde71190efd6154d95ce1b9d16fcfa608a.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/b3de9c824ba1d4cd6d81190f.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/e0fe9925cc2c683834a80f11.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/0bd162d9f2d3572c65911a988a13632762d0c307.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/ac6eddc451da81cb2ac1708a5266d01609243155.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/1bd5ad6e8416d98080cb4a48.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/3c6d55fbb2fb43169d0508ca20a4462309f7d36c.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/faedab64034f78f0daf3664a79310a55b2191c8a.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/2fdda3cc7cd98d10b05af088213fb80e7aec90f9.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/b8014a90f603738d9536f39bb31bb051f819ec0f.jpg");urls.add("http://hiphotos.baidu.com/baidu/pic/item/2fdda3cc7cd98d10b05af088213fb80e7aec90f9.jpg");imageAdapter = new ImageAdapter(urls, this);images_ga.setAdapter(imageAdapter);images_ga.setOnItemClickListener(this);images_ga.setOnItemSelectedListener(new OnItemSelectedListener() {@Overridepublic void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {num=arg2;Log.i("mahua", "ItemSelected=="+arg2);GalleryWhetherStop();}@Overridepublic void onNothingSelected(AdapterView<?> arg0) {// TODO Auto-generated method stub}});}@Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {Log.i("GOLF", "第"+arg2+"个被点击了");
    }/*** 判断Gallery滚动是否停止,如果停止则加载当前页面的图片*/private void GalleryWhetherStop() {Runnable runnable = new Runnable() {public void run() {try {int index =0;index = num;Thread.sleep(1000);if (index == num) {url.add(urls.get(num));if(num!=0 && urls.get(num-1)!=null) {url.add(urls.get(num-1));}if(num!=urls.size()-1 && urls.get(num+1)!=null) {url.add(urls.get(num+1));}Message m = new Message();m.what = 1;mHandler.sendMessage(m);}} catch (Exception e) {e.printStackTrace();}}};new Thread(runnable).start();
    }// 加载图片的异步任务class LoadImageTask extends AsyncTask<String, Void, Bitmap> {@Override  protected void onCancelled() {  // TODO Auto-generated method stub  super.onCancelled();  }  @Override  protected void onPostExecute(Bitmap result) {  // TODO Auto-generated method stub        super.onPostExecute(result);  }  @Overrideprotected Bitmap doInBackground(String... params) {Bitmap bitmap = null;try {String url = params[0];boolean isExists = Files.compare(url); //这里是自己写的工具类,判断本地缓存是否已经下载过图片if (isExists == false) {//如果不存在就去下载图片Net net = new Net();byte[] data = net.downloadResource(MyActivity.this, url);bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);imagesCache.put(url, bitmap); // 把下载好的图片保存到缓存中Files.saveImage(url, data);} else {//如果存在直接读取缓存图片byte[] data = Files.readImage(url);bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);imagesCache.put(url, bitmap); // 把下载好的图片保存到缓存中}Message m = new Message();//图片加载完成通知重新加载m.what = 0;mHandler.sendMessage(m);} catch (Exception e) {e.printStackTrace();}return bitmap;}}private Handler mHandler = new Handler() {public void handleMessage(Message msg) {try {switch (msg.what) {case 0: {imageAdapter.notifyDataSetChanged();break;}case 1: {for(int i=0; i<url.size(); i++) {LoadImageTask task = new LoadImageTask();//异步加载图片task.execute(url.get(i));Log.i("mahua", url.get(i));}url.clear();}}super.handleMessage(msg);} catch (Exception e) {e.printStackTrace();}}
    };
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {if(keyCode==KeyEvent.KEYCODE_BACK){System.exit(0);}return super.onKeyDown(keyCode, event);
    }
    }import java.util.List;
    import android.content.Context;
    import android.content.res.AssetManager;
    import android.content.res.TypedArray;
    import android.graphics.Bitmap;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.Gallery;
    import android.widget.ImageView;public class ImageAdapter extends BaseAdapter {
    public static final BaseAdapter Adapter = null;
    private List<String> imageUrls; // 图片地址list
    private Context context;
    int mGalleryItemBackground;public ImageAdapter(List<String> imageUrls, Context context) {
    this.imageUrls = imageUrls;
    this.context = context;
    // /*
    // * 使用在res/values/attrs.xml中的<declare-styleable>定义 的Gallery属性.
    // */
    TypedArray a = context.obtainStyledAttributes(R.styleable.Gallery1);
    /* 取得Gallery属性的Index id */
    mGalleryItemBackground = a.getResourceId(
    R.styleable.Gallery1_android_galleryItemBackground, 0);
    /* 让对象的styleable属性能够反复使用 */
    a.recycle();
    }
    public int getCount() {
    return imageUrls.size();
    }
    public Object getItem(int position) {
    return imageUrls.get(position);
    }
    public long getItemId(int position) {
    return position;
    }
    public View getView(int position, View convertView, ViewGroup parent) {
    Bitmap image;
    ImageView view = new ImageView(context);
    image = MyActivity.imagesCache.get(imageUrls.get(position));
    // 从缓存中读取图片
    if (image == null) {
    image = MyActivity.imagesCache.get("background_non_load");
    }
    // 设置所有图片的资源地址
    view.setImageBitmap(image);
    view.setScaleType(ImageView.ScaleType.FIT_XY);
    view.setLayoutParams(new Gallery.LayoutParams(240, 320));
    view.setBackgroundResource(mGalleryItemBackground);
    /* 设置Gallery背景图 */
    return view;
    }
    }attrs.xml
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    <declare-styleable name="TogglePrefAttrs">
    <attr name="android:preferenceLayoutChild" />
    </declare-styleable><!-- These are the attributes that we want to retrieve from the theme
    in view/Gallery1.java -->
    <declare-styleable name="Gallery1">
    <attr name="android:galleryItemBackground" />
    </declare-styleable><declare-styleable name="LabelView">
    <attr name="text" format="string" />
    <attr name="textColor" format="color" />
    <attr name="textSize" format="dimension" />
    </declare-styleable>
    </resources>


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

android Gallery实现异步加载网络图片相关推荐

  1. Android之ListView异步加载网络图片(优化缓存机制)

    网上关于这个方面的文章也不少,基本的思路是线程+缓存来解决.下面提出一些优化: 1.采用线程池 2.内存缓存+文件缓存 3.内存缓存中网上很多是采用SoftReference来防止堆溢出,这儿严格限制 ...

  2. Android使用ImageLoader异步加载网络图片(一)读取单张图片

    这里我写的是读取单张的图片从网络读取,和listview多张图片的读取首先是单张的读取这篇博客只写了读取单张的读取多张的下一篇写 此例子的代码 已上传资源页 由于昨天时间比较紧所以,这个Demo 的源 ...

  3. android 图片加载 软引用_Android 异步加载网络图片并缓存到本地 软引用 学习分享(转)...

    迪 王. 于 星期四, 20/02/2014 - 21:36 提交 在android应用开发的时候,加载网络图片是一个非常重要的部分,很多图片不可能放在本地,所以就必须要从服务器或者网络读取图片. 软 ...

  4. iOS开发swift版异步加载网络图片(带缓存和缺省图片)

    iOS开发之swift版异步加载网络图片 与SDWebImage异步加载网络图片的功能相似,只是代码比较简单,功能没有SD的完善与强大,支持缺省添加图片,支持本地缓存. 异步加载图片的核心代码如下: ...

  5. ios开发多线程篇--异步加载网络图片GCD

    一.异步加载网络图片 1.ATS (1)简介 从iOS9.0开始,如果按照以前的方式写代码,在访问网络的时候 ,会报以下警告信息: App Transport Security has blocked ...

  6. IOS开发之异步加载网络图片并缓存本地实现瀑布流(一)

    2019独角兽企业重金招聘Python工程师标准>>> 版权声明:本文为博主原创文章,未经博主允许不得转载. [objc] view plaincopy </pre>&l ...

  7. 异步加载网络图片 可同时加载多张

    按照惯例先上传效果图: 图片效果只是加载一张网络上的图片,实际开发中放在list_item中都可以,有两种方法实现,就不贴代码了. 传送门:源代码下载地址:android 实现图片异步加载

  8. android异步加载图片并缓存到内存和sd卡上,Android批量图片加载经典系列——采用二级缓存、异步加载网络图片...

    http://www.cnblogs.com/jerehedu/p/4560119.html 2015-06-08 09:20 by 杰瑞教育, 232 阅读, 1 评论, 收藏, 编辑一.问题描述 ...

  9. 网络相册:Gallery+AsyncTask+URLConnection 实现异步加载网络图片

    这个例子需要点基础知识: Gallery的使用,这个网上的例子多的是 如何使用AsyncTask,这个可以看这里<[Android]异步任务AsyncTask使用解析> 使用URLConn ...

最新文章

  1. php有哪几种,php数据类型包括哪几种
  2. 收藏吧!产品再要求实现这个功能,就把这篇转给他!
  3. ffmpeg:Codec for stream 0 does not use global headers but container format requires global headers
  4. iapp启动图代码_代码神器:拒绝重复编码,这款IDEA插件了解一下.....
  5. [mybatis]Mapper XML Files_获取自增主键的值
  6. python基础笔记_python基础学习笔记
  7. __str__是什么函数_PHP str_shuffle()函数与示例
  8. mysql按select导出_mysql 导出select结果到文本的几种方式
  9. Java泛型中extends和super的区别?
  10. File类里的静态字段
  11. 从深圳到底特律——我的出国求学之路
  12. 早上内部资源共享讨论发言稿
  13. Find Any File for Mac(本地文件搜索查找工具)
  14. java 实现用户登陆代码_Java Web用户登录实例代码
  15. VBa运行c语言程序,Excel VBA编程详解
  16. 面试之springboot是什么?
  17. yii2 之图片上传插件fileinput使用说明
  18. 找不到msvcr120.dll
  19. 数学建模常用算法—优劣解距离法(TOPSIS)
  20. mmdetectionV2.x版本 训练自己的VOC数据集

热门文章

  1. iOS:实现邮件和短信发送的简单示例
  2. Zookeeper+Kafka集群搭建
  3. 流行的JavaScript库 ——jQuery
  4. JavaScript escape/unescape 编码的 Java 实现
  5. Sublime Text 3快捷键大全
  6. maven spring hibernate shiro
  7. 无法安装某些更新或程序
  8. GridView自带的分页功能的实现
  9. 【iOS-Cocos2d游戏开发之七】添加/删除系统组件,并解决View设置透明会影响View中的其他组件的问题!...
  10. selenium+python谷歌驱动配置