Android ListView从网络获取图片及文字显示

时间:2023-03-08 20:38:11

上一篇文章说的是ListView展示本地的图片以及文本,这一篇说一下如何从网络获取图片以及文本来显示。事实上,一般是先获取Josn或sml数据,然后解释显示。我们先从网上获取xml,然后对其进行解析,最后显示在ListView上。具体步骤:

  • 客户端发出请求,获取xml
  • 客户端异步解析xml
  • ListView将解析完的数据显示

一、Android客户端

Android ListView从网络获取图片及文字显示

(1)xml布局文件

        mainxml,就是一个ListView。

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical">
  6. <ListView
  7. android:id="@+id/list"
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:divider="#b5b5b5"
  11. android:dividerHeight="1dp"
  12. android:listSelector="@drawable/list_selector" />
  13. </LinearLayout>

ListView的每一行的布局,list_raw.xml,看一下结构图:

Android ListView从网络获取图片及文字显示

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="wrap_content"
  5. android:background="@drawable/list_selector"
  6. android:orientation="horizontal"
  7. android:padding="5dip" >
  8. <!--  ListView最左边的缩略图 -->
  9. <LinearLayout android:id="@+id/thumbnail"
  10. android:layout_width="wrap_content"
  11. android:layout_height="wrap_content"
  12. android:padding="3dip"
  13. android:layout_alignParentLeft="true"
  14. android:background="@drawable/image_bg"
  15. android:layout_marginRight="5dip">
  16. <ImageView
  17. android:id="@+id/list_image"
  18. android:layout_width="50dip"
  19. android:layout_height="50dip"
  20. android:src="@drawable/rihanna"/>
  21. </LinearLayout>
  22. <!-- 歌曲名-->
  23. <TextView
  24. android:id="@+id/title"
  25. android:layout_width="wrap_content"
  26. android:layout_height="wrap_content"
  27. android:layout_alignTop="@+id/thumbnail"
  28. android:layout_toRightOf="@+id/thumbnail"
  29. android:text="Rihanna Love the way lie"
  30. android:textColor="#040404"
  31. android:typeface="sans"
  32. android:textSize="15dip"
  33. android:textStyle="bold"/>
  34. <!-- 歌手名 -->
  35. <TextView
  36. android:id="@+id/artist"
  37. android:layout_width="fill_parent"
  38. android:layout_height="wrap_content"
  39. android:layout_below="@id/title"
  40. android:textColor="#343434"
  41. android:textSize="10dip"
  42. android:layout_marginTop="1dip"
  43. android:layout_toRightOf="@+id/thumbnail"
  44. android:text="Just gona stand there and ..." />
  45. <!-- 歌曲播放时间 -->
  46. <TextView
  47. android:id="@+id/duration"
  48. android:layout_width="wrap_content"
  49. android:layout_height="wrap_content"
  50. android:layout_alignParentRight="true"
  51. android:layout_alignTop="@id/title"
  52. android:gravity="right"
  53. android:text="5:45"
  54. android:layout_marginRight="5dip"
  55. android:textSize="10dip"
  56. android:textColor="#10bcc9"
  57. android:textStyle="bold"/>
  58. <!-- 进入播放 -->
  59. <ImageView android:layout_width="wrap_content"
  60. android:layout_height="wrap_content"
  61. android:src="@drawable/arrow"
  62. android:layout_alignParentRight="true"
  63. android:layout_centerVertical="true"/>
  64. </RelativeLayout>

另外我们打算使用几个特效,一个是当点击列表项目的时候,项目背景色改变,其实就是一个selector;另一个就是用shape美化视觉效果,具体看xml代码:

1.list_selector.xml      

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">
  3. <!-- Selector style for listrow -->
  4. <item
  5. android:state_selected="false"
  6. android:state_pressed="false"
  7. android:drawable="@drawable/gradient_bg" />
  8. <item android:state_pressed="true"
  9. android:drawable="@drawable/gradient_bg_hover" />
  10. <item android:state_selected="true"
  11. android:state_pressed="false"
  12. android:drawable="@drawable/gradient_bg_hover" />
  13. </selector>

Android ListView从网络获取图片及文字显示

2.gradient_bg.xml,是默认背景梯度风格

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:shape="rectangle">
  4. <!--  Gradient Bg for listrow -->
  5. <gradient
  6. android:startColor="#f1f1f2"
  7. android:centerColor="#e7e7e8"
  8. android:endColor="#cfcfcf"
  9. android:angle="270" />
  10. </shape>

3.gradient_bg_hover.xml 梯度风格在悬停状态

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:shape="rectangle">
  4. <!-- Gradient BgColor for listrow Selected -->
  5. <gradient
  6. android:startColor="#18d7e5"
  7. android:centerColor="#16cedb"
  8. android:endColor="#09adb9"
  9. android:angle="270" />
  10. </shape>

4.image_bg.xml 在图片周围的白色边条

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
  3. <item>
  4. <shape
  5. android:shape="rectangle">
  6. <stroke android:width="1dp" android:color="#dbdbdc" />
  7. <solid android:color="#FFFFFF" />
  8. </shape>
  9. </item>
  10. </layer-list>

以上效果基本上都用到了shape,对此不了解的可以去查看相关资料。上面就是全部的xml布局文件,下面将开始写代码。

(2)主要代码

代码部分主要涉及到一下几个功能,重写ListView的适配器(BaseAdapter),从网络获取图片,图片缓存的处理,xml的解析。

①重写ListView的适配器,这部分可以参考上一篇文章,LazyAdapter.java

  1. import java.util.ArrayList;
  2. import java.util.HashMap;
  3. import android.app.Activity;
  4. import android.content.Context;
  5. import android.view.LayoutInflater;
  6. import android.view.View;
  7. import android.view.ViewGroup;
  8. import android.widget.BaseAdapter;
  9. import android.widget.ImageView;
  10. import android.widget.TextView;
  11. public class LazyAdapter extends BaseAdapter {
  12. private Activity activity;
  13. private ArrayList<HashMap<String, String>> data;
  14. private static LayoutInflater inflater=null;
  15. public ImageLoader imageLoader; //用来下载图片的类,后面有介绍
  16. public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
  17. activity = a;
  18. data=d;
  19. inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  20. imageLoader=new ImageLoader(activity.getApplicationContext());
  21. }
  22. public int getCount() {
  23. return data.size();
  24. }
  25. public Object getItem(int position) {
  26. return position;
  27. }
  28. public long getItemId(int position) {
  29. return position;
  30. }
  31. public View getView(int position, View convertView, ViewGroup parent) {
  32. View vi=convertView;
  33. if(convertView==null)
  34. vi = inflater.inflate(R.layout.list_row, null);
  35. TextView title = (TextView)vi.findViewById(R.id.title); // 标题
  36. TextView artist = (TextView)vi.findViewById(R.id.artist); // 歌手名
  37. TextView duration = (TextView)vi.findViewById(R.id.duration); // 时长
  38. ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // 缩略图
  39. HashMap<String, String> song = new HashMap<String, String>();
  40. song = data.get(position);
  41. // 设置ListView的相关值
  42. title.setText(song.get(CustomizedListView.KEY_TITLE));
  43. artist.setText(song.get(CustomizedListView.KEY_ARTIST));
  44. duration.setText(song.get(CustomizedListView.KEY_DURATION));
  45. imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
  46. return vi;
  47. <em>  }
  48. }</em>

②网络获取图片的类,ImageLoader.java:

  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileOutputStream;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import java.net.HttpURLConnection;
  8. import java.net.URL;
  9. import java.util.Collections;
  10. import java.util.Map;
  11. import java.util.WeakHashMap;
  12. import java.util.concurrent.ExecutorService;
  13. import java.util.concurrent.Executors;
  14. import android.app.Activity;
  15. import android.content.Context;
  16. import android.graphics.Bitmap;
  17. import android.graphics.BitmapFactory;
  18. import android.widget.ImageView;
  19. public class ImageLoader {
  20. MemoryCache memoryCache=new MemoryCache();
  21. FileCache fileCache;
  22. private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
  23. ExecutorService executorService;
  24. public ImageLoader(Context context){
  25. fileCache=new FileCache(context);
  26. executorService=Executors.newFixedThreadPool(5);
  27. }
  28. final int stub_id = R.drawable.no_image;
  29. public void DisplayImage(String url, ImageView imageView)
  30. {
  31. imageViews.put(imageView, url);
  32. Bitmap bitmap=memoryCache.get(url);
  33. if(bitmap!=null)
  34. imageView.setImageBitmap(bitmap);
  35. else
  36. {
  37. queuePhoto(url, imageView);
  38. imageView.setImageResource(stub_id);
  39. }
  40. }
  41. private void queuePhoto(String url, ImageView imageView)
  42. {
  43. PhotoToLoad p=new PhotoToLoad(url, imageView);
  44. executorService.submit(new PhotosLoader(p));
  45. }
  46. private Bitmap getBitmap(String url)
  47. {
  48. File f=fileCache.getFile(url);
  49. //从sd卡
  50. Bitmap b = decodeFile(f);
  51. if(b!=null)
  52. return b;
  53. //从网络
  54. try {
  55. Bitmap bitmap=null;
  56. URL imageUrl = new URL(url);
  57. HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
  58. conn.setConnectTimeout(30000);
  59. conn.setReadTimeout(30000);
  60. conn.setInstanceFollowRedirects(true);
  61. InputStream is=conn.getInputStream();
  62. OutputStream os = new FileOutputStream(f);
  63. Utils.CopyStream(is, os);
  64. os.close();
  65. bitmap = decodeFile(f);
  66. return bitmap;
  67. } catch (Exception ex){
  68. ex.printStackTrace();
  69. return null;
  70. }
  71. }
  72. //解码图像用来减少内存消耗
  73. private Bitmap decodeFile(File f){
  74. try {
  75. //解码图像大小
  76. BitmapFactory.Options o = new BitmapFactory.Options();
  77. o.inJustDecodeBounds = true;
  78. BitmapFactory.decodeStream(new FileInputStream(f),null,o);
  79. //找到正确的刻度值,它应该是2的幂。
  80. final int REQUIRED_SIZE=70;
  81. int width_tmp=o.outWidth, height_tmp=o.outHeight;
  82. int scale=1;
  83. while(true){
  84. if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
  85. break;
  86. width_tmp/=2;
  87. height_tmp/=2;
  88. scale*=2;
  89. }
  90. BitmapFactory.Options o2 = new BitmapFactory.Options();
  91. o2.inSampleSize=scale;
  92. return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
  93. } catch (FileNotFoundException e) {}
  94. return null;
  95. }
  96. /任务队列
  97. private class PhotoToLoad
  98. {
  99. public String url;
  100. public ImageView imageView;
  101. public PhotoToLoad(String u, ImageView i){
  102. url=u;
  103. imageView=i;
  104. }
  105. }
  106. class PhotosLoader implements Runnable {
  107. PhotoToLoad photoToLoad;
  108. PhotosLoader(PhotoToLoad photoToLoad){
  109. this.photoToLoad=photoToLoad;
  110. }
  111. @Override
  112. public void run() {
  113. if(imageViewReused(photoToLoad))
  114. return;
  115. Bitmap bmp=getBitmap(photoToLoad.url);
  116. memoryCache.put(photoToLoad.url, bmp);
  117. if(imageViewReused(photoToLoad))
  118. return;
  119. BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
  120. Activity a=(Activity)photoToLoad.imageView.getContext();
  121. a.runOnUiThread(bd);
  122. }
  123. }
  124. boolean imageViewReused(PhotoToLoad photoToLoad){
  125. String tag=imageViews.get(photoToLoad.imageView);
  126. if(tag==null || !tag.equals(photoToLoad.url))
  127. return true;
  128. return false;
  129. }
  130. //用于显示位图在UI线程
  131. class BitmapDisplayer implements Runnable
  132. {
  133. Bitmap bitmap;
  134. PhotoToLoad photoToLoad;
  135. public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
  136. public void run()
  137. {
  138. if(imageViewReused(photoToLoad))
  139. return;
  140. if(bitmap!=null)
  141. photoToLoad.imageView.setImageBitmap(bitmap);
  142. else
  143. photoToLoad.imageView.setImageResource(stub_id);
  144. }
  145. }
  146. public void clearCache() {
  147. memoryCache.clear();
  148. fileCache.clear();
  149. }
  150. }

③xml解析,xml的解析有很多方法,这里采用进行dom方式的xml解析。

  1. import java.io.IOException;
  2. import java.io.StringReader;
  3. import java.io.UnsupportedEncodingException;
  4. import javax.xml.parsers.DocumentBuilder;
  5. import javax.xml.parsers.DocumentBuilderFactory;
  6. import javax.xml.parsers.ParserConfigurationException;
  7. import org.apache.http.HttpEntity;
  8. import org.apache.http.HttpResponse;
  9. import org.apache.http.client.ClientProtocolException;
  10. import org.apache.http.client.methods.HttpPost;
  11. import org.apache.http.impl.client.DefaultHttpClient;
  12. import org.apache.http.util.EntityUtils;
  13. import org.w3c.dom.Document;
  14. import org.w3c.dom.Element;
  15. import org.w3c.dom.Node;
  16. import org.w3c.dom.NodeList;
  17. import org.xml.sax.InputSource;
  18. import org.xml.sax.SAXException;
  19. import android.util.Log;
  20. public class XMLParser {
  21. // 构造方法
  22. public XMLParser() {
  23. }
  24. /**
  25. * 从URL获取XML使HTTP请求
  26. * @param url string
  27. * */
  28. public String getXmlFromUrl(String url) {
  29. String xml = null;
  30. try {
  31. // defaultHttpClient
  32. DefaultHttpClient httpClient = new DefaultHttpClient();
  33. HttpPost httpPost = new HttpPost(url);
  34. HttpResponse httpResponse = httpClient.execute(httpPost);
  35. HttpEntity httpEntity = httpResponse.getEntity();
  36. xml = EntityUtils.toString(httpEntity);
  37. } catch (UnsupportedEncodingException e) {
  38. e.printStackTrace();
  39. } catch (ClientProtocolException e) {
  40. e.printStackTrace();
  41. } catch (IOException e) {
  42. e.printStackTrace();
  43. }
  44. return xml;
  45. }
  46. /**
  47. * 获取XML DOM元素
  48. * @param XML string
  49. * */
  50. public Document getDomElement(String xml){
  51. Document doc = null;
  52. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  53. try {
  54. DocumentBuilder db = dbf.newDocumentBuilder();
  55. InputSource is = new InputSource();
  56. is.setCharacterStream(new StringReader(xml));
  57. doc = db.parse(is);
  58. } catch (ParserConfigurationException e) {
  59. Log.e("Error: ", e.getMessage());
  60. return null;
  61. } catch (SAXException e) {
  62. Log.e("Error: ", e.getMessage());
  63. return null;
  64. } catch (IOException e) {
  65. Log.e("Error: ", e.getMessage());
  66. return null;
  67. }
  68. return doc;
  69. }
  70. /** 获取节点值
  71. * @param elem element
  72. */
  73. public final String getElementValue( Node elem ) {
  74. Node child;
  75. if( elem != null){
  76. if (elem.hasChildNodes()){
  77. for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
  78. if( child.getNodeType() == Node.TEXT_NODE  ){
  79. return child.getNodeValue();
  80. }
  81. }
  82. }
  83. }
  84. return "";
  85. }
  86. /**
  87. * 获取节点值
  88. * @param Element node
  89. * @param key string
  90. * */
  91. public String getValue(Element item, String str) {
  92. NodeList n = item.getElementsByTagName(str);
  93. return this.getElementValue(n.item(0));
  94. }
  95. }

④程序缓存的处理,主要是内存缓存+文件缓存。内存缓存中网上很多是采用SoftReference来防止堆溢出:

MemoryCache.java:

  1. import java.lang.ref.SoftReference;
  2. import java.util.Collections;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. import android.graphics.Bitmap;
  6. public class MemoryCache {
  7. private Map<String, SoftReference<Bitmap>> cache=Collections.synchronizedMap(new HashMap<String, SoftReference<Bitmap>>());//软引用
  8. public Bitmap get(String id){
  9. if(!cache.containsKey(id))
  10. return null;
  11. SoftReference<Bitmap> ref=cache.get(id);
  12. return ref.get();
  13. }
  14. public void put(String id, Bitmap bitmap){
  15. cache.put(id, new SoftReference<Bitmap>(bitmap));
  16. }
  17. public void clear() {
  18. cache.clear();
  19. }
  20. }

FileCache.java

  1. import java.io.File;
  2. import android.content.Context;
  3. public class FileCache {
  4. private File cacheDir;
  5. public FileCache(Context context){
  6. //找一个用来缓存图片的路径
  7. if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
  8. cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
  9. else
  10. cacheDir=context.getCacheDir();
  11. if(!cacheDir.exists())
  12. cacheDir.mkdirs();
  13. }
  14. public File getFile(String url){
  15. String filename=String.valueOf(url.hashCode());
  16. File f = new File(cacheDir, filename);
  17. return f;
  18. }
  19. public void clear(){
  20. File[] files=cacheDir.listFiles();
  21. if(files==null)
  22. return;
  23. for(File f:files)
  24. f.delete();
  25. }
  26. }

⑤还有一个读取流的工具类,Utils.java:

  1. import java.io.InputStream;
  2. import java.io.OutputStream;
  3. public class Utils {
  4. public static void CopyStream(InputStream is, OutputStream os)
  5. {
  6. final int buffer_size=1024;
  7. try
  8. {
  9. byte[] bytes=new byte[buffer_size];
  10. for(;;)
  11. {
  12. int count=is.read(bytes, 0, buffer_size);
  13. if(count==-1)
  14. break;
  15. os.write(bytes, 0, count);
  16. is.close();
  17. os.close();
  18. }
  19. }
  20. catch(Exception ex){}
  21. }
  22. }

还可以像下面这样表达,方法是一样的,就是表达形式上不同:

  1. public static byte[] readStream(InputStream inStream) throws Exception{
  2. ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
  3. byte[] buffer = new byte[1024];
  4. int len = -1;
  5. while( (len=inStream.read(buffer)) != -1){
  6. outSteam.write(buffer, 0, len);
  7. }
  8. outSteam.close();
  9. inStream.close();
  10. return outSteam.toByteArray();
  11. }
  12. }

最后就是主Activity的代码了,

  1. package com.example.androidhive;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import org.w3c.dom.Document;
  5. import org.w3c.dom.Element;
  6. import org.w3c.dom.NodeList;
  7. import android.app.Activity;
  8. import android.os.Bundle;
  9. import android.view.View;
  10. import android.widget.AdapterView;
  11. import android.widget.AdapterView.OnItemClickListener;
  12. import android.widget.ListView;
  13. public class CustomizedListView extends Activity {
  14. // 所有的静态变量
  15. static final String URL = "http://api.androidhive.info/music/music.xml";//xml目的地址,打开地址看一下
  16. // XML 节点
  17. static final String KEY_SONG = "song"; // parent node
  18. static final String KEY_ID = "id";
  19. static final String KEY_TITLE = "title";
  20. static final String KEY_ARTIST = "artist";
  21. static final String KEY_DURATION = "duration";
  22. static final String KEY_THUMB_URL = "thumb_url";
  23. ListView list;
  24. LazyAdapter adapter;
  25. @Override
  26. public void onCreate(Bundle savedInstanceState) {
  27. super.onCreate(savedInstanceState);
  28. setContentView(R.layout.main);
  29. ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
  30. XMLParser parser = new XMLParser();
  31. String xml = parser.getXmlFromUrl(URL); // 从网络获取xml
  32. Document doc = parser.getDomElement(xml); // 获取 DOM 节点
  33. NodeList nl = doc.getElementsByTagName(KEY_SONG);
  34. // 循环遍历所有的歌节点 <song>
  35. for (int i = 0; i < nl.getLength(); i++) {
  36. // 新建一个 HashMap
  37. HashMap<String, String> map = new HashMap<String, String>();
  38. Element e = (Element) nl.item(i);
  39. //每个子节点添加到HashMap关键= >值
  40. map.put(KEY_ID, parser.getValue(e, KEY_ID));
  41. map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
  42. map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
  43. map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
  44. map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
  45. // HashList添加到数组列表
  46. songsList.add(map);
  47. }
  48. list=(ListView)findViewById(R.id.list);
  49. adapter=new LazyAdapter(this, songsList);
  50. list.setAdapter(adapter);
  51. //为单一列表行添加单击事件
  52. list.setOnItemClickListener(new OnItemClickListener() {
  53. @Override
  54. public void onItemClick(AdapterView<?> parent, View view,
  55. int position, long id) {
  56. //这里可以*发挥,比如播放一首歌曲等等
  57. }
  58. });
  59. }
  60. }

最后看一下效果:

Android ListView从网络获取图片及文字显示

源码:http://download.****.net/detail/javadxz/6846569