解析网络json数据并展示到ListView上

      网易新闻看起来很简洁,左边是一张图片,右边是一些文字信息,这样的排版是十分常见的,给人的感觉就是简洁明了,下面通过解析网络json数据并展示到ListView上,来实现同样的效果,效果图如下:



1.数据来源于网上json数据的解析,网址为http://mrobot.pcauto.com.cn/v2/cms/channels/3?pageNo=1&pageSize=20&v=4.0.0(可能过段时间就失效了),如果想了解json解析或者获取json数据接口,参照:http://blog.csdn.net/ljw124213/article/details/52313758。json的格式如下(这里只解析title,image和pubDate三个字段):



2.先写出解析此json数据的实体类:

<span style="font-size:18px;"><span style="font-size:18px;">package com.example.listview;

import java.util.ArrayList;

public class CarBean {
	
	public ArrayList<Car>data;
	
	public static class Car{
		public String title;
		public String pubDate;
		public String image;
	}
}</span><span style="font-size:14px;">
</span></span>

3.解析json数据的工具类:

<span style="font-size:18px;"><span style="font-size:18px;">package com.example.listview;

import com.google.gson.Gson;

public class JsonUtils {
	public static CarBean parseJson(String jsonString){
		Gson gson = new Gson();
		CarBean cb = gson.fromJson(jsonString, CarBean.class);
		return cb;
	}
}</span></span>
注意:使用Gson解析的话,必须先下载Gson的jar包,放到工程的libs目录下,下载地址:http://download.csdn.net/detail/ljw124213/9612607

4.从网络上下载数据的工具类:

<span style="font-size:18px;"><span style="font-size:18px;">package com.example.listview;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetUtils {

	public static byte[] getNetData(String urlString){
		try {
			URL url = new URL(urlString);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			
			conn.setRequestMethod("GET");
			conn.setReadTimeout(5000);
			conn.setConnectTimeout(5000);
			
			byte[] result = null;
			if (conn.getResponseCode() == 200) {
				InputStream is = conn.getInputStream();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				while((len=is.read(buffer))!=-1){
					baos.write(buffer, 0, len);
				}
				result = baos.toByteArray();
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}</span></span>

5.下载android-smart-image-view开源框架,把其src下的部分复制到自己工程的src下面,下载地址(带有使用详解):http://download.csdn.net/detail/ljw124213/9630820


6.准备工作完成之后,下面开始实现具体功能,创建一个异步任务类,来下载网络数据:

<span style="font-size:18px;">package com.example.listview;

import java.util.ArrayList;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import com.example.listview.CarBean.Car;

public class DownAsynctask extends AsyncTask<String, Void, byte[]>{

	ArrayList<Car>data;
	MyAdapter adapter;
	Context context;
	
	public DownAsynctask(ArrayList<Car> data, MyAdapter adapter, Context context) {
		super();
		this.data = data;
		this.adapter = adapter;
		this.context = context;
	}

	/*
	 * 当主线程中调用executeOnExecutor方法或execute方法时,会调用此方法
	 */
	@Override
	protected byte[] doInBackground(String... params) {
		//下载网络数据
		return NetUtils.getNetData(params[0]);
	}

	/*
	 * doInBackground方法执行之后会执行此方法,并把结果传过来
	 */
	@Override
	protected void onPostExecute(byte[] result) {
		super.onPostExecute(result);
		if (result != null) {
			//把从网络上获取的byte类型的数据转换为String字符串
			String jsonString = new String(result);
			//用json解析工具来解析该字符串数据
			CarBean cb = JsonUtils.parseJson(jsonString);
			//取出data数据,并保存到集合中
			data.addAll(cb.data);
			//刷新数据
			adapter.notifyDataSetChanged();
		}else {
			Toast.makeText(context, "网络异常", Toast.LENGTH_SHORT).show();
		}
	}
}</span>


 

7.创建一个数据适配器,用来加载数据:

<span style="font-size:18px;">package com.example.listview;

import java.util.ArrayList;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.listview.CarBean.Car;
import com.loopj.android.image.SmartImageView;

public class MyAdapter extends BaseAdapter{

	ArrayList<Car> data;
	Context context;
	
	public MyAdapter(ArrayList<Car> data, Context context) {
		super();
		this.data = data;
		this.context = context;
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		//初始化holder对象
		ViewHold holder;
		if(convertView == null){
			//把条目布局转化为view对象
			convertView = View.inflate(context, R.layout.item, null);
			//初始化holder对象,并初始化holder中的控件
			holder = new ViewHold();
			holder.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
			holder.tv_date = (TextView) convertView.findViewById(R.id.tv_date);
			holder.iv = (SmartImageView) convertView.findViewById(R.id.iv);
			//给当前view做个标记,并把数据存到该tag中
			convertView.setTag(holder);
			
		}else {
			 //如果当前view存在,则直接从中取出其保存的控件及数据
			holder = (ViewHold) convertView.getTag();
		}
		//通过position获取当前item的car数据,从car数据中取出title、pubDate和image
		Car car = data.get(position);
		holder.tv_title.setText(car.title);
		holder.tv_date.setText(car.pubDate);
		
		//使用SmartImageView的setImageUrl方法下载图片
		holder.iv.setImageUrl(car.image);
		
		return convertView;
	}

	/*
	 * 用来存放item布局中控件的holder类
	 */
	class ViewHold{
		SmartImageView iv; //显示图片的控件,注意是SmartImageView
		TextView tv_title; //显示标题的控件
		TextView tv_date;  //显示日期的控件
	}
}</span>


 
8.在MainActivity中进行数据的汇总: 

<span style="font-size:18px;">package com.example.listview;

import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;

import com.example.listview.CarBean.Car;

public class MainActivity extends Activity {

	private ListView lv;
	private ArrayList<Car> data;
	private MyAdapter adapter;
	private boolean flag = false;
	private int pageNo = 1;
	private ExecutorService es;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//初始化listview控件
		lv = (ListView) findViewById(R.id.lv);
		//存放json解析的数据的集合
		data = new ArrayList<Car>();
		//自定义适配器
		adapter = new MyAdapter(data,this);
		
		//给listview设置一个底部view(必须在设置数据之前)
		View footView = View.inflate(this, R.layout.foot, null);
		lv.addFooterView(footView);
		
		//给listview设置适配器
		lv.setAdapter(adapter);
		
		//使用线程池来实现异步任务的多线程下载
		es = Executors.newFixedThreadPool(10);
		new DownAsynctask(data,adapter,this).executeOnExecutor(es, "http://mrobot.pcauto.com.cn/v2/cms/channels/3?pageNo="+pageNo+"&pageSize=20&v=4.0.0");
		
		/*
		 * 对listview设置滚动监听事件,实现分页加载数据
		 */
		lv.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				//如果停止了滑动且滑动到了结尾,则更新数据,加载下一页
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && flag == true) {
					pageNo += 1;
					new DownAsynctask(data,adapter,MainActivity.this).executeOnExecutor(es, "http://mrobot.pcauto.com.cn/v2/cms/channels/3?pageNo="+pageNo+"&pageSize=20&v=4.0.0");
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				//判断是否滑动到了结尾
				if (firstVisibleItem + visibleItemCount == totalItemCount) {
					flag = true;
				}else {
					flag = false;
				}
			}
		});
	}
}</span>

 
9.ListView对应的布局文件activity_main.xml: 

<span style="font-size:18px;"><span style="font-size:18px;"><span style="font-size:18px;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout></span></span></span>


10.ListView对应的item的布局文件item.xml:

<span style="font-size:18px;"><span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    
    <!-- 注意:这里的ImageView要改为包名+SmartImageView -->
    <com.loopj.android.image.SmartImageView
        android:id="@+id/iv"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/ic_launcher"/>
    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginLeft="15dp"
        android:orientation="vertical">
        <TextView 
            android:id="@+id/tv_title"
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:layout_marginTop="10dp"
            android:textSize="20sp"/>
        <TextView 
            android:id="@+id/tv_date"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:textSize="16sp"
            android:textColor="#aaa"/>
    </LinearLayout>

</LinearLayout></span></span>


11.ListView尾布局对应的布局文件footer.xml:

<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal"
    android:gravity="center" >
    
	<TextView 
	    android:layout_height="wrap_content"
	    android:layout_width="wrap_content"
	    android:text="拼命加载中..."/>
	<ProgressBar 
	    android:layout_width="wrap_content"
	    android:layout_height="match_parent"/>
</LinearLayout></span>


提示:此数据接口可能很快就不能用来,如果需要测试的话,可以把原数据放到tomcat服务器中进行测试,下面是完整数据:

{
    "data": [
        {
            "articleType": "n",
            "count": 29,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/8/14733163729178590_600.jpg",
            "id": "8562073",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/08/g_8562073_1473339813478_240x160.jpg",
            "mtime": 1473351348000,
            "pubDate": "2016-09-09",
            "title": "新福特翼虎购车手册 家用中配足够实用",
            "ups": 26,
            "url": "http://www.pcauto.com.cn/teach/856/8562073.html"
        },
        {
            "articleType": "n",
            "count": 37,
            "downs": 0,
            "firstImg": "http://img0.pcauto.com.cn/pcauto/1608/31/8655654_toutu_thumb.jpg",
            "id": "8655654",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8655654_1472800030976_240x160.jpg",
            "mtime": 1473351337000,
            "pubDate": "2016-09-09",
            "title": "年轻人第一台车 10万左右精品车型推荐",
            "ups": 130,
            "url": "http://www.pcauto.com.cn/teach/865/8655654.html"
        },
        {
            "articleType": "n",
            "count": 35,
            "downs": 0,
            "firstImg": "http://img0.pcauto.com.cn/pcauto/1609/06/8719572_toutu_thumb.jpg",
            "id": "8719572",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/06/g_8719572_1473152785181_240x160.jpg",
            "mtime": 1473264982000,
            "pubDate": "2016-09-08",
            "title": "豪门不“壕” 4款入门豪华SUV仅售23万起",
            "ups": 143,
            "url": "http://www.pcauto.com.cn/teach/871/8719572.html"
        },
        {
            "articleType": "n",
            "count": 40,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/1/14727375445822660_600.jpg",
            "id": "8705572",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/07/g_8705572_1473242245557_240x160.jpg",
            "mtime": 1473264969000,
            "pubDate": "2016-09-08",
            "title": "明锐对比英朗 当欧洲绅士遇上美国大汉",
            "ups": 52,
            "url": "http://www.pcauto.com.cn/teach/870/8705572.html"
        },
        {
            "articleType": "n",
            "count": 68,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/6/14731526553913750_600.jpg",
            "id": "8719262",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/06/g_8719262_1473151845818_240x160.jpg",
            "mtime": 1473153591000,
            "pubDate": "2016-09-06",
            "title": "新晋英伦长轴距座驾 捷豹XFL实拍解析",
            "ups": 299,
            "url": "http://www.pcauto.com.cn/teach/871/8719262.html"
        },
        {
            "articleType": "n",
            "count": 100,
            "downs": 0,
            "firstImg": "http://img0.pcauto.com.cn/pcauto/1609/07/8695292_999_thumb.jpg",
            "id": "8695292",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/01/g_8695292_1472695974218_240x160.jpg",
            "mtime": 1473137438000,
            "pubDate": "2016-09-06",
            "title": "15万元搞定 四款独立后悬挂合资SUV推荐",
            "ups": 117,
            "url": "http://www.pcauto.com.cn/teach/869/8695292.html"
        },
        {
            "articleType": "n",
            "count": 84,
            "downs": 0,
            "firstImg": "http://img0.pcauto.com.cn/pcauto/1609/06/8718677_xin1000_thumb.jpg",
            "id": "8718677",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/05/g_8718677_1473061488223_240x160.jpg",
            "mtime": 1473092132000,
            "pubDate": "2016-09-06",
            "title": "8万元选靠谱SUV 4款新推自主车型推荐",
            "ups": 91,
            "url": "http://www.pcauto.com.cn/teach/871/8718677.html"
        },
        {
            "articleType": "n",
            "count": 96,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20168/29/14724733055558460_600.jpg",
            "id": "8683971",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8683971_1472803720871_240x160.jpg",
            "mtime": 1473005791000,
            "pubDate": "2016-09-05",
            "title": "凯美瑞对比雅阁 谁才是日系中级车霸主",
            "ups": 65,
            "url": "http://www.pcauto.com.cn/teach/868/8683971.html"
        },
        {
            "articleType": "n",
            "count": 136,
            "downs": 0,
            "firstImg": "http://img0.pcauto.com.cn/pcauto/1609/04/8716791_00_thumb.jpg",
            "id": "8716791",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/04/g_8716791_1473002216143_240x160.jpg",
            "mtime": 1473005746000,
            "pubDate": "2016-09-05",
            "title": "精华都在这里 成都车展最值得关注的SUV",
            "ups": 390,
            "url": "http://www.pcauto.com.cn/teach/871/8716791.html"
        },
        {
            "articleType": "n",
            "count": 26,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/4/14729794978954170_600.jpg",
            "id": "8716391",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/04/g_8716391_1472979896686_240x160.jpg",
            "mtime": 1472980188000,
            "pubDate": "2016-09-04",
            "title": "2016成都车展:静态评测奔驰新一代威霆",
            "ups": 312,
            "url": "http://www.pcauto.com.cn/teach/871/8716391.html"
        },
        {
            "articleType": "n",
            "count": 32,
            "downs": 0,
            "firstImg": "http://img0.pcauto.com.cn/pcauto/1609/01/8700555_8207206_03_thumb.jpg",
            "id": "8700555",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/01/g_8700555_1472716638381_240x160.jpg",
            "mtime": 1472919329000,
            "pubDate": "2016-09-04",
            "title": "入门性价比爆炸 新款致炫购车手册",
            "ups": 91,
            "url": "http://www.pcauto.com.cn/teach/870/8700555.html"
        },
        {
            "articleType": "n",
            "count": 70,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/2/14728310541595730_600.jpg",
            "id": "8712133",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8712133_1472831164431_240x160.jpg",
            "mtime": 1472832200000,
            "pubDate": "2016-09-03",
            "title": "2016成都车展:静态评测北京现代胜达",
            "ups": 468,
            "url": "http://www.pcauto.com.cn/teach/871/8712133.html"
        },
        {
            "articleType": "n",
            "count": 41,
            "downs": 0,
            "firstImg": "http://img0.pcauto.com.cn/pcauto/1609/02/8710078_1000_thumb.jpg",
            "id": "8710078",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8710078_1472810381352_240x160.jpg",
            "mtime": 1472817162000,
            "pubDate": "2016-09-02",
            "title": "2016成都车展:静态评测新款玛莎拉蒂总裁",
            "ups": 299,
            "url": "http://www.pcauto.com.cn/teach/871/8710078.html"
        },
        {
            "articleType": "n",
            "count": 62,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/2/14728116986128820_600.jpg",
            "id": "8711094",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8711094_1472812405190_240x160.jpg",
            "mtime": 1472812618000,
            "pubDate": "2016-09-02",
            "title": "2016成都车展:静态评测大众新桑塔纳",
            "ups": 1053,
            "url": "http://www.pcauto.com.cn/teach/871/8711094.html"
        },
        {
            "articleType": "n",
            "count": 28,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/2/14728073809221840_600.jpg",
            "id": "8710334",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8710334_1472807999865_240x160.jpg",
            "mtime": 1472808197000,
            "pubDate": "2016-09-02",
            "title": "2016成都车展:静态体验北京现代悦纳",
            "ups": 247,
            "url": "http://www.pcauto.com.cn/teach/871/8710334.html"
        },
        {
            "articleType": "n",
            "count": 31,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/2/14728054816668520_600.jpg",
            "id": "8710116",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8710116_1472805803455_240x160.jpg",
            "mtime": 1472806069000,
            "pubDate": "2016-09-02",
            "title": "2016成都车展:静态评测东南DX3",
            "ups": 247,
            "url": "http://www.pcauto.com.cn/teach/871/8710116.html"
        },
        {
            "articleType": "n",
            "count": 60,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/2/14728006933643890_600.jpg",
            "id": "8709146",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8709146_1472801055169_240x160.jpg",
            "mtime": 1472801551000,
            "pubDate": "2016-09-02",
            "title": "2016成都车展:静态评测宝马X1混动版",
            "ups": 806,
            "url": "http://www.pcauto.com.cn/teach/870/8709146.html"
        },
        {
            "articleType": "n",
            "count": 87,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/2/14727918621883140_600.jpg",
            "id": "8708181",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8708181_1472793809972_240x160.jpg",
            "mtime": 1472794520000,
            "pubDate": "2016-09-02",
            "title": "2016成都车展:静态评测东风本田竞瑞",
            "ups": 533,
            "url": "http://www.pcauto.com.cn/teach/870/8708181.html"
        },
        {
            "articleType": "n",
            "count": 34,
            "downs": 0,
            "firstImg": "http://img0.pcauto.com.cn/pcauto/1609/02/8704693_toutu_thumb.jpg",
            "id": "8704693",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8704693_1472787714022_240x160.jpg",
            "mtime": 1472793542000,
            "pubDate": "2016-09-02",
            "title": "冲击市场有力竞争者 新科沃兹购车手册",
            "ups": 117,
            "url": "http://www.pcauto.com.cn/teach/870/8704693.html"
        },
        {
            "articleType": "n",
            "count": 111,
            "downs": 0,
            "firstImg": "http://img.pcauto.com.cn/images/pcautogallery/modle/article/20169/2/14727803654960920_600.jpg",
            "id": "8706132",
            "image": "http://img0.pcauto.com.cn/pcauto/1609/02/g_8706132_1472781925547_240x160.jpg",
            "mtime": 1472781940000,
            "pubDate": "2016-09-02",
            "title": "7座对标汉兰达 斯柯达KODIAQ实拍解析",
            "ups": 104,
            "url": "http://www.pcauto.com.cn/teach/870/8706132.html"
        }
    ],
    "pageNo": 1,
    "pageSize": 20,
    "total": 200
}


要将JSON数据解析并应用到ListView,您可以按照以下步骤进行: 1. 获取JSON数据 您可以使用HttpURLConnection或OkHttp等网络库来获取JSON数据。确保在获取数据时处理好异常情况,例如网络不可用或无法连接到服务器。 2. 解析JSON数据 Android提供了一个org.json包,其包含用于解析JSON数据的类。您可以使用JSONObject和JSONArray类来解析JSON对象和数组。 例如,假设您从服务器上获取了以下JSON数据: ``` { "books": [ { "title": "The Great Gatsby", "author": "F. Scott Fitzgerald" }, { "title": "To Kill a Mockingbird", "author": "Harper Lee" } ] } ``` 您可以使用以下代码解析数据: ```java try { JSONObject jsonObject = new JSONObject(jsonData); JSONArray jsonArray = jsonObject.getJSONArray("books"); ArrayList<Book> bookList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject bookObj = jsonArray.getJSONObject(i); String title = bookObj.getString("title"); String author = bookObj.getString("author"); bookList.add(new Book(title, author)); } // 将解析数据应用到ListView BookListAdapter adapter = new BookListAdapter(this, bookList); ListView listView = findViewById(R.id.list_view); listView.setAdapter(adapter); } catch (JSONException e) { e.printStackTrace(); } ``` 3. 应用数据ListView 创建一个ListView并使用适配器将数据应用到ListView。您可以创建自己的适配器或使用Android提供的默认适配器,例如ArrayAdapter或SimpleAdapter。 例如,假设您要将解析的书籍数据应用到ListView,您可以创建一个自定义适配器: ```java public class BookListAdapter extends ArrayAdapter<Book> { private LayoutInflater inflater; public BookListAdapter(Context context, ArrayList<Book> books) { super(context, 0, books); inflater = LayoutInflater.from(context); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = inflater.inflate(R.layout.list_item_book, parent, false); holder = new ViewHolder(); holder.titleTextView = convertView.findViewById(R.id.title_text_view); holder.authorTextView = convertView.findViewById(R.id.author_text_view); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } Book book = getItem(position); holder.titleTextView.setText(book.getTitle()); holder.authorTextView.setText(book.getAuthor()); return convertView; } private static class ViewHolder { TextView titleTextView; TextView authorTextView; } } ``` 其Book是一个自定义类,用于存储书籍的标题和作者信息。 现在,您可以将适配器应用到ListView: ```java BookListAdapter adapter = new BookListAdapter(this, bookList); ListView listView = findViewById(R.id.list_view); listView.setAdapter(adapter); ``` 请注意,您需要在布局文件定义ListView和list_item_book布局。 list_item_book布局应该包含用于显示书名和作者的TextView元素。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值