Android实现Listview异步加载网络图片并动态更新的方法

 更新时间:2016年08月13日 09:48:51   作者:Intergret  
这篇文章主要介绍了Android实现Listview异步加载网络图片并动态更新的方法,结合实例形式详细分析了ListView异步加载数据的操作步骤与具体实现技巧,需要的朋友可以参考下

本文实例讲述了Android实现Listview异步加载网络图片并动态更新的方法。分享给大家供大家参考,具体如下:

应用实例:解析后台返回的数据,把每条都显示在ListView中,包括活动图片、店名、活动详情、地址、电话和距离等。

在布局文件中ListView的定义:

<ListView
android:id="@id/maplistview" 
android:background="@drawable/bg" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:cacheColorHint="#00000000" 
android:divider="@drawable/separator" 
android:dividerHeight="2.0px" 
android:layout_below="@id/mapseparator"
/>

在布局文件ListViewItem,中定义活动图片、店名、活动详情、地址、电话和距离的布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/RelativeLayout01" 
android:layout_width="fill_parent" 
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" 
android:paddingBottom="2dip" 
android:paddingLeft="2dip" 
android:paddingRight="2dip">
<ImageView
android:paddingTop="2dip" 
android:layout_alignParentLeft="true" 
android:layout_width="80px" 
android:layout_height="80px" 
android:id="@+id/maplistviewitemImage"/>
<TextView
android:layout_height="wrap_content" 
android:textSize="17dip" 
android:layout_width="fill_parent" 
android:id="@+id/maplistviewitemshopname"
android:layout_toRightOf="@id/maplistviewitemImage"
android:textColor="#000000"/>
<TextView
android:layout_height="wrap_content" 
android:layout_width="fill_parent" 
android:layout_alignParentLeft="true" 
android:layout_below="@+id/maplistviewitemImage" 
android:id="@+id/maplistviewitemActi" 
android:textColor="#6C6C6C"/>
<TextView
android:layout_height="wrap_content" 
android:layout_width="fill_parent" 
android:layout_alignParentLeft="true" 
android:layout_below="@+id/maplistviewitemActi" 
android:id="@+id/maplistviewitemaddr" 
android:textColor="#6C6C6C" 
android:singleLine="true"/>
<TextView
android:layout_height="wrap_content" 
android:layout_width="fill_parent" 
android:layout_alignParentLeft="true" 
android:layout_below="@+id/maplistviewitemaddr" 
android:id="@+id/maplistviewitemtelphone" 
android:textColor="#6C6C6C" 
android:singleLine="true"/>
</RelativeLayout>

(1)定义类MapListImageAndText管理ListViewItem中控件的内容

package com.google.zxing.client.android.AsyncLoadImage;
public class MapListImageAndText {
    private String imageUrl;
    private String shopname;
    private String activitynifo;
    private String address;
    private String telephone;
    private String distance;
    public MapListImageAndText(String imageUrl, String shopname, String activitynifo, String address, String telephone,String distance) {
      this.imageUrl = imageUrl;
      this.shopname = shopname;
      this.activitynifo = activitynifo;
      this.address = address;
      this.telephone = telephone;
      this.distance=distance;
    }
    public String getImageUrl() {
      return imageUrl;
    }
    public String getShopname() {
      return shopname;
    }
    public String getActivitynifo() {
      return activitynifo;
    }
    public String getAddress() {
      return address;
    }
    public String getTelephone() {
      return telephone;
    }
    public String getDistance() {
      return distance;
    }
}

(2)定义类MapListViewCache实例化ListViewItem中的控件

package com.google.zxing.client.android.AsyncLoadImage;
import com.google.zxing.client.android.R;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class MapListViewCache {
    private View baseView;
    private TextView shopname;
    private TextView activitynifo;
    private TextView address;
    private TextView telephone;
    private TextView distance;
    private ImageView imageView;
    public MapListViewCache(View baseView) {
      this.baseView = baseView;
    }
    public TextView getShopname() {
      if (shopname == null) {
        shopname = (TextView) baseView.findViewById(R.id.maplistviewitemshopname);
      }
      return shopname;
    }
    public TextView getActivitynifo() {
      if (activitynifo == null) {
        activitynifo = (TextView) baseView.findViewById(R.id.maplistviewitemActi);
      }
      return activitynifo;
    }
    public TextView getAddress() {
      if (address == null) {
        address = (TextView) baseView.findViewById(R.id.maplistviewitemaddr);
      }
      return address;
    }
    public TextView getTelephone() {
      if (telephone == null) {
        telephone = (TextView) baseView.findViewById(R.id.maplistviewitemtelphone);
      }
      return telephone;
    }
    public ImageView getImageView() {
      if (imageView == null) {
        imageView = (ImageView) baseView.findViewById(R.id.maplistviewitemImage);
      }
      return imageView;
    }
    public TextView getDistance() {
      if (distance == null) {
        distance = (TextView) baseView.findViewById(R.id.maplistviewitemdistance);
      }
      return distance;
    }
}

(3)定义类AsyncImageLoader,开启线程下载指定图片

package com.google.zxing.client.android.AsyncLoadImage;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
public class AsyncImageLoader {
   private HashMap<String, SoftReference<Drawable>> imageCache;
     public AsyncImageLoader() {
       imageCache = new HashMap<String, SoftReference<Drawable>>();
     }
     public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
       if (imageCache.containsKey(imageUrl)) {
         SoftReference<Drawable> softReference = imageCache.get(imageUrl);
         Drawable drawable = softReference.get();
         if (drawable != null) {
           return drawable;
         }
       }
       final Handler handler = new Handler() {
         public void handleMessage(Message message) {
           imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
         }
       };
       new Thread() {
         @Override
         public void run() {
           Drawable drawable = loadImageFromUrl(imageUrl);
           imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
           Message message = handler.obtainMessage(0, drawable);
           handler.sendMessage(message);
         }
       }.start();
       return null;
     }
    public static Drawable loadImageFromUrl(String url) {
      URL m;
      InputStream i = null;
      try {
        m = new URL(url);
        i = (InputStream) m.getContent();
      } catch (MalformedURLException e1) {
        e1.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
      Drawable d = Drawable.createFromStream(i, "src");
      return d;
    }
     public interface ImageCallback {
       public void imageLoaded(Drawable imageDrawable, String imageUrl);
     }
}

(4)定义类MapListImageAndTextListAdapter继承ArrayAdapter,用于创建AsyncImageLoader实例,并指定控件的内容

package com.google.zxing.client.android.AsyncLoadImage;
import java.util.List;
import com.google.zxing.client.android.R;
import com.google.zxing.client.android.AsyncLoadImage.AsyncImageLoader.ImageCallback;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MapListImageAndTextListAdapter extends ArrayAdapter<MapListImageAndText> {
    private ListView listView;
    private AsyncImageLoader asyncImageLoader;
    public MapListImageAndTextListAdapter(Activity activity, List<MapListImageAndText> imageAndTexts, ListView listView) {
      super(activity, 0, imageAndTexts);
      this.listView = listView;
      asyncImageLoader = new AsyncImageLoader();
    }
    public View getView(int position, View convertView, ViewGroup parent) {
      Activity activity = (Activity) getContext();
      // Inflate the views from XML
      View rowView = convertView;
      MapListViewCache viewCache;
      if (rowView == null) {
        LayoutInflater inflater = activity.getLayoutInflater();
        rowView = inflater.inflate(R.layout.maplistviewitem, null);
        viewCache = new MapListViewCache(rowView);
        rowView.setTag(viewCache);
      } else {
        viewCache = (MapListViewCache) rowView.getTag();
      }
      MapListImageAndText imageAndText = getItem(position);
      // Load the image and set it on the ImageView
      String imageUrl = imageAndText.getImageUrl();
      ImageView imageView = viewCache.getImageView();
      imageView.setTag(imageUrl);
      Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl, new ImageCallback() {
        public void imageLoaded(Drawable imageDrawable, String imageUrl) {
          ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);
          if (imageViewByTag != null) {
            imageViewByTag.setImageDrawable(imageDrawable);
          }
        }
      });
      if (cachedImage == null) {
        imageView.setImageResource(R.drawable.refresh);
      }else{
        imageView.setImageDrawable(cachedImage);
      }
      // Set the text on the TextView
      TextView shopname = viewCache.getShopname();
      shopname.setText(imageAndText.getShopname());
      TextView activitynifo = viewCache.getActivitynifo();
      activitynifo.setText(imageAndText.getActivitynifo());
      TextView address = viewCache.getAddress();
      address.setText(imageAndText.getAddress());
      TextView telephone = viewCache.getTelephone();
      telephone.setText(imageAndText.getTelephone());
      TextView distance = viewCache.getDistance();
      distance.setText(imageAndText.getDistance());
      return rowView;
    }
}

(5)主程序中Listview与MapListImageAndTextListAdapter的捆绑

//tuangoupoints为对后台传回来的数据解析后得到的字符串
String[] mtuangoupoints =tuangoupoints.split("@");
List<MapListImageAndText> dataArray=new ArrayList<MapListImageAndText>();
for(int i=0; i<mtuangoupoints.length;i++){
  String[] tonepoint=mtuangoupoints[i].split("#");
  String shopname=String.valueOf(i+1)+tonepoint[2];
  String activityinfo=tonepoint[1];
  String address=tonepoint[6];
  String telephone=tonepoint[7];
  String imageurl=tonepoint[8];
  String distance=tonepoint[5];
  MapListImageAndText test=new MapListImageAndText(imageurl,shopname,activityinfo,address,telephone,distance);
  dataArray.add(test);
}
MapListImageAndTextListAdapter adapter=new MapListImageAndTextListAdapter(this, dataArray, mlistView);
mlistView.setAdapter(adapter);

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android视图View技巧总结》、《Android编程之activity操作技巧总结》、《Android操作SQLite数据库技巧总结》、《Android操作json格式数据技巧总结》、《Android数据库操作技巧总结》、《Android文件操作技巧汇总》、《Android编程开发之SD卡操作方法汇总》、《Android开发入门与进阶教程》、《Android资源操作技巧汇总》及《Android控件用法总结

希望本文所述对大家Android程序设计有所帮助。

相关文章

  • 教你如何搭建android源代码repo仓库

    教你如何搭建android源代码repo仓库

    这篇文章主要介绍了如何搭建android源代码repo仓库,如果你的开发是基于AOSP源码来建仓,那么搭建repo服务器和部署自己的repo仓库就是非常必要的工作了,本文给大家详细介绍搭建过程,感兴趣的朋友一起看看吧
    2022-07-07
  • Android库项目中的资源ID冲突的解决方法

    Android库项目中的资源ID冲突的解决方法

    本篇文章主要介绍了Android库项目中的资源ID冲突的解决方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-03-03
  • android 对话框弹出位置和透明度的设置具体实现方法

    android 对话框弹出位置和透明度的设置具体实现方法

    在android中我们经常会用AlertDialog来显示对话框。通过这个对话框是显示在屏幕中心的。但在某些程序中,要求对话框可以显示在不同的位置。
    2013-07-07
  • Android编程实现仿美团或淘宝的多级分类菜单效果示例【附demo源码下载】

    Android编程实现仿美团或淘宝的多级分类菜单效果示例【附demo源码下载】

    这篇文章主要介绍了Android编程实现仿美团或淘宝的多级分类菜单效果,结合实例形式分析了Android多级菜单的实现技巧,并附带demo源码供读者下载参考,需要的朋友可以参考下
    2017-01-01
  • SQLite数据库在Android中的使用小结

    SQLite数据库在Android中的使用小结

    SQLIte是一款轻型的数据库,占用资源非常低,在嵌入式设备中,可能只需几百k的内存,这篇文章主要介绍了SQLite数据库在Android中的使用,需要的朋友可以参考下
    2024-07-07
  • AndriodStudio利用ListView和数据库实现简单学生管理

    AndriodStudio利用ListView和数据库实现简单学生管理

    这篇文章主要为大家详细介绍了AndriodStudio利用ListView和数据库实现简单学生管理,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • RxJava取消订阅的各种方式的实现

    RxJava取消订阅的各种方式的实现

    这篇文章主要介绍了RxJava取消订阅的各种方式的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-09-09
  • Android学习笔记——Menu介绍(二)

    Android学习笔记——Menu介绍(二)

    这次将继续上一篇文章没有讲完的Menu的学习,上下文菜单(Context menu)和弹出菜单(Popup menu)
    2014-10-10
  • android与asp.net服务端共享session的方法详解

    android与asp.net服务端共享session的方法详解

    这篇文章主要给大家介绍了关于android与asp.net服务端如何共享session的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋们下面随着小编来一起学习学习下吧。
    2017-09-09
  • 浅析Android手机卫士接收短信指令执行相应操作

    浅析Android手机卫士接收短信指令执行相应操作

    通过广播接收者,接收到短信,对短信内容进行判断,如果为我们指定的值就执行相应的操作。本文给大家介绍Android手机卫士接收短信指令执行相应操作,感兴趣的朋友参考下吧
    2016-04-04

最新评论