Android 列表 下拉加载 上拉刷新 附源码

/*网上找的源码,做了些修改。至于原作者是谁我也不清楚了,不过看注释应该不是国内的,反正我这个菜鸟没这种水平。
**修复了上次刷新时间显示及刷新丢失当前第一项的问题。加了一组假数据测试localDate。
*贴出的是主界面的代码,源码见附件
**/

package com.refreash;

import android.os.Bundle;
import android.app.Activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import com.widget.CustomListView;
import com.widget.CustomListView.IXListViewListener;

import android.os.Handler;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class MainActivity extends Activity implements IXListViewListener {
	private CustomListView mListView;
	private ArrayAdapter<String> mAdapter;
	private ArrayList<String> items = new ArrayList<String>();
	public SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private Handler mHandler;
	private int start = 0;
	private String date;
	ArrayList<String> localdate=new ArrayList<String>();//假数据数组
	
	//给假数组赋值
	private void initDate(){
		for(int i=0;i<100;i++){
			this.localdate.add(i+"");
		}
	}
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initDate();//获取数据
		geneItems();//加载数据
		mListView = (CustomListView) findViewById(R.id.xListView);
		MainActivity.this.date=sdf.format(new Date());		
		mListView.setRefreshTime(date);//获取首次更新时间
		mListView.setPullLoadEnable(true);
		mAdapter = new ArrayAdapter<String>(this, R.layout.list_item, items);
		mListView.setAdapter(mAdapter);
//		mListView.setPullLoadEnable(false);
//		mListView.setPullRefreshEnable(false);
		mListView.setXListViewListener(this);
		mHandler = new Handler();
	}
     
	private void geneItems() {
		for (int i = 0; i != 20; ++i) {//每次加载二十项
			if(start<localdate.size()){
			items.add("refresh cnt " + localdate.get(start++).toString());
			}else{
				Toast.makeText(getApplicationContext(), "已经到底啦^_^", 2000).show();
				return ;
			}
		}
	}

	private void onLoad() {
		mListView.stopRefresh();
		mListView.stopLoadMore();
		mListView.setRefreshTime(date);
		MainActivity.this.date=sdf.format(new Date());
	}
	
	@Override
	public void onRefresh() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				/**
				 * .....
				 * initDate();
				 * ......
				 * if(返回值==null){
				 * start=0;
				 * toast.maketext(..."没有最新消息"...).show();
				 * ......
				 * }else{
				 * start=0;
				 * items.clear();
				 * ......
				 * ......
				 * }
				 * */
				start = 0;
				items.clear();
				geneItems();
				// mAdapter.notifyDataSetChanged();
				mAdapter = new ArrayAdapter<String>(MainActivity.this, R.layout.list_item, items);
				mListView.setAdapter(mAdapter);
				onLoad();
			}
		}, 2000);
	}

	@Override
	public void onLoadMore() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				geneItems();
				mAdapter.notifyDataSetChanged();
				onLoad();
			}
		}, 2000);
	}

}

相关推荐