Listview实现分页下载

时间:2022-01-10 20:26:14
分析:
* 1.初始控件,展示第一页数据
* 2.设置触发条件
* 1.设置滚动监听
* 2.判断是否在底部
* 3.判断是否停止滚动
* 4.更改网络请求参数为下一页
* 5.异步网络请求
* 6.解析成新的集合
* 7.把新的集合添加到之前的集合中
* 8.更新数据
* 3.添加 加载过程中对话框提示正在加载的功能

layout.xml

<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" > <ListView
android:id="@+id/listView"
android:layout_height="match_parent"
android:layout_width="wrap_content"></ListView> </RelativeLayout>

listview_news.xml

<?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" >
<TextView
android:id="@+id/tv_sublect"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
/>
<ImageView
android:id="@+id/img_cover"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/> </LinearLayout>

HttpUtils.java

package HttpUtils;

import java.io.IOException;
import java.io.StringReader; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils; import android.graphics.Bitmap;
import android.graphics.BitmapFactory; public class HttpUtils {
//从网络下载json数据
public static String getJsonDataByIntetnet(String path){
byte[] buffer= getByteArrayByIntetnet(path);
if(buffer != null && buffer.length != 0){
return new String(buffer);
}
return null; }
//从网络获取字节数组
public static byte[] getByteArrayByIntetnet(String path){
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(path);
HttpResponse httpResponse = client.execute(httpGet);
if(200 == httpResponse.getStatusLine().getStatusCode()){
HttpEntity entity = httpResponse.getEntity();
return EntityUtils.toByteArray(entity);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}return null; }
//从网络上获取Bitmap对象
public static Bitmap getBitmapByIntetnet(byte[] byteArray){
if(byteArray != null && byteArray.length != 0){
return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
}
return null; }
}

ParseJson.java

package parserJson;

import java.util.ArrayList;
import java.util.List; import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject; import com.example.News; public class ParserJson {
public static List<News> parseJson(String json){
try {
JSONObject jsonObject = new JSONObject(json);
JSONObject jsonObject2 = jsonObject.getJSONObject("paramz");
JSONArray jsonArray = jsonObject2.getJSONArray("feeds");
List<News>dataList = new ArrayList<News>();
News news;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject3 = jsonArray.getJSONObject(i);
news = new News();
JSONObject jsonObject4 = jsonObject3.getJSONObject("data");
news.setTv_subject(jsonObject4.getString("subject"));
news.setImg_cover(jsonObject4.getString("cover"));
dataList.add(news);
}
return dataList;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null; }
}

Constants.java

package com.example;
/**
* 将需要下载数据的网址隔开,实现分页下载的目的
* @author my
*
*/
public class Constants {
public static final String pathBefore="http://litchiapi.jstv.com/api/GetFeeds?column=0&PageSize=10&pageIndex=";
public static final String pathAfter = "&val=100511D3BE5301280E0992C73A9DEC41";
}

News.java

package com.example;
/**
* 新闻类
* @author my
*
*/
public class News {
private String tv_subject;
private String img_cover;
public String getTv_subject() {
return tv_subject;
}
public void setTv_subject(String tv_subject) {
this.tv_subject = tv_subject;
}
public String getImg_cover() {
return img_cover;
}
public void setImg_cover(String img_cover) {
this.img_cover = img_cover;
}
@Override
public String toString() {
return "News [tv_subject=" + tv_subject + ", img_cover=" + img_cover
+ "]";
} }

UpdateNewView.java

package com.example;

import java.util.List;

/**
* 更新视图
* @author my
*
*/
public interface UpdateNewView {
public void updateNewView(List<News> dataList);
}

UpdateImageView.java

package com.example;

import android.graphics.Bitmap;
/**
* 更新图片
* @author my
*
*/
public interface UpdateImageView {
public void updateImageView(Bitmap bitmap);
}

DownLoadData_AsyncTask.java

package com.example;

import java.util.List;

import parserJson.ParserJson;
import HttpUtils.HttpUtils;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
/**
* 异步任务类下载数据
* @author my
*
*/
public class MyAsyncTask extends AsyncTask<String, Integer, List<News>>{
private Context context;
private UpdateNewView updateNewView;
private String TAG = "MainActivity";
private ProgressDialog progressDialog; public MyAsyncTask(Context context, UpdateNewView updateNewView) {
super();
this.context = context;
this.updateNewView = updateNewView;
}
/**
* 在执行异步下载之前调用
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
//创建进度条对话框
progressDialog = new ProgressDialog(context);
//设置标题
progressDialog.setTitle("加载数据");
//设置信息
progressDialog.setMessage("玩命加载...");
//进度条展示
progressDialog.show();
}
/**
* 执行异步下载数据操作
*/
@Override
protected List<News> doInBackground(String... params) {
//从网络获取json数据
String jsonDataByIntetnet = HttpUtils.getJsonDataByIntetnet(params[0]);
//解析json数据到集合
List<News> dataList = ParserJson.parseJson(jsonDataByIntetnet); return dataList;
}
/**
* 接收doInBacground传过来的数据,并回传给接口的实现方法中
*/
@Override
protected void onPostExecute(List<News> result) {
super.onPostExecute(result);
//移除对话框,展示页面
progressDialog.dismiss();
if(result != null && result.size() != 0){
updateNewView.updateNewView(result);//接口回调
}
}
}

DownLoadImg_AsyncTask.java

package com.example;

import HttpUtils.HttpUtils;
import android.graphics.Bitmap;
import android.os.AsyncTask;
/**
* 异步任务实现类下载图片
* @author my
*
*/
public class DownLoadImgAsyncTask extends AsyncTask<String, Integer, Bitmap>{
private UpdateImageView updateImageView; public DownLoadImgAsyncTask(UpdateImageView updateImageView) {
super();
this.updateImageView = updateImageView;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Bitmap doInBackground(String... params) {
byte[] byteArrayByIntetnet = HttpUtils.getByteArrayByIntetnet(params[0]);
Bitmap bitmapByIntetnet = HttpUtils.getBitmapByIntetnet(byteArrayByIntetnet); return bitmapByIntetnet;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if(result != null ){
updateImageView.updateImageView(result);
}
}
}

Main.java

package com.example;

import java.util.ArrayList;
import java.util.List; import com.example.day09_listview_page.R;
import com.example.day09_listview_page.R.drawable;
import com.example.day09_listview_page.R.id;
import com.example.day09_listview_page.R.layout; import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ListView;
import android.widget.TextView; public class MainActivity extends Activity {
private int index = 1;
private ListView listView;
private boolean isBottom;
private MyAdapter adapter;
//设置数据集合
private List<News> dataList1 = new ArrayList<News>(); @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
listView = (ListView) findViewById(R.id.listView);
//设置数据
/**
* 创建异步任务下载数据
*/
new MyAsyncTask(MainActivity.this,new UpdateNewView() { @Override
public void updateNewView(List<News> dataList) {
//填充第一页数据
dataList1.remove(dataList1);
dataList1.addAll(dataList);
//创建适配器
adapter = new MyAdapter();
//适配器控件设置适配器
listView.setAdapter(adapter);
}
}).execute(Constants.pathBefore+index+Constants.pathAfter);
/**
* 设置listView滚动监听事件:添加新的页面的数据
*/
listView.setOnScrollListener(new OnScrollListener() {
/**
* 当滚动状态改变的时候调用
*/
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
//滚动停止并且页面滑动到底部,执行异步下载下一页的操作
if(scrollState==SCROLL_STATE_IDLE && isBottom){
index += 1;//页数加1
new MyAsyncTask(MainActivity.this,new UpdateNewView() {
@Override
public void updateNewView(List<News> dataList) {
dataList1.addAll(dataList1);//添加回传过来的集合
adapter.notifyDataSetChanged();//通知刷新数据,listview里面的item发生变化时调用该方法更新数据
}
}).execute(Constants.pathBefore+index+Constants.pathAfter);
} }
/**
* 当listView滚动的时候调用
*/
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
isBottom =(firstVisibleItem + visibleItemCount==totalItemCount) ; }
}); }
class MyAdapter extends BaseAdapter{ @Override
public int getCount() {
return dataList1.size();
} @Override
public Object getItem(int position) {
return dataList1.get(position);
} @Override
public long getItemId(int position) {
return position;
}
//为适配器控件的每条item的view组件设置数据
@Override
public View getView(int position, View convertView, final ViewGroup parent) {
View view = convertView;
final ViewHolder viewHolder;
if(view == null){
view= View.inflate(MainActivity.this, R.layout.listview_news, null);
viewHolder = new ViewHolder();
viewHolder.tv_subject = (TextView)view.findViewById(R.id.tv_sublect);
viewHolder.img_cover = (ImageView) view.findViewById(R.id.img_cover);
view.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) view.getTag();
}
News news = dataList1.get(position);
viewHolder.tv_subject.setText(news.getTv_subject());
//设置默认图片
viewHolder.img_cover.setImageResource(R.drawable.ic_launcher);
final String imgPath = news.getImg_cover();
//解决图片错乱问题,给图片设置一个标记
viewHolder.img_cover.setTag(imgPath);
//创建一个异步任务下载图片
new DownLoadImgAsyncTask(new UpdateImageView() { @Override
public void updateImageView(Bitmap bitmap) {
//适配器控件通过标记找到view控件
ImageView imageView= (ImageView) parent.findViewWithTag(imgPath);
//设置图片
            if(iamgeView != null){
  imageView.setImageBitmap(bitmap);
            }
}
}).execute(imgPath);
return view;
} }
class ViewHolder{
private TextView tv_subject;
private ImageView img_cover;
} }