android上拉刷新下拉加载

本文用的XlistView的上拉刷新下拉加载


android上拉刷新下拉加载_第1张图片


主Activity

package org.com.cctest;

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

import org.com.cctest.view.XListView;
import org.com.cctest.view.XListView.IXListViewListener;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ArrayAdapter;

public class XListViewActivity extends Activity implements IXListViewListener {
	private final String TAG="XListViewActivity";
	private XListView mListView;
	private ArrayAdapter<String> mAdapter;
	private ArrayList<String> items = new ArrayList<String>();
	private Handler mHandler;
	private int start = 0;
	private static int refreshCnt = 0;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xlistview);
		geneItems();
		mListView = (XListView) findViewById(R.id.xListView);
		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) {
			//没有更新的时候start的值为0,但是显示出来的值是++start 为1
			items.add("refresh cnt " + (++start));
		}
	}

	private void onLoad() {
		mListView.stopRefresh();
		mListView.stopLoadMore();
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(currentTime);
		mListView.setRefreshTime(dateString);
	}
//上拉刷新的方法,刷新完后再调用onLoad方法去停止更新加载
	@Override
	public void onRefresh() {
		Log.i(TAG, "刷新最新");
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				//start的值会随着不断的上拉数值会不断的增加 1 2 3 4 5 6 。。。
				start = ++refreshCnt;
				//清空ArrayList中的数据
				items.clear();
				//获取数据
				geneItems();
				// 加载数据显示在view中
				mAdapter = new ArrayAdapter<String>(XListViewActivity.this, R.layout.list_item, items);
				//显示在布局Activity 中
				mListView.setAdapter(mAdapter);
				//显示更新的时间
				onLoad();
			}
		}, 2000);
	}
//下拉加载时此时start是20,继续在20基础上循环
	@Override
	public void onLoadMore() {
		Log.i(TAG, "加载更多");
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				geneItems();
				mAdapter.notifyDataSetChanged();
				onLoad();
			}
		}, 2000);
	}

}


其他的是XlistView工具类和布局文件就不一一贴出来了


下载链接 http://pan.baidu.com/s/1o83qk9k




你可能感兴趣的:(android上拉刷新下拉加载)