Android 分页组件

如果你用过 新浪微薄Android客户端,或者其他Android电子市场,你会发现,他们的内容是不是滚不完,会根据网络进行下一页数据加载。好把,今天在这里我就和大家分享下我写的一个分页类,让大家以后写带分页界面越来越容易。

 

package com.ffly.demo

import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

public class NduoaPageAdapter <T> extends BaseAdapter{
	private boolean mHasLeft = true;
	private int mPageSize;
	private List<T> mResult = null;
	private Context mContext = null;
	private LayoutInflater mInflater;
	private int mRes;
	private int mLoadingRes;
	private INduoaPageAdapter<T> mCallback;
	private int mStart=0;
	
      //res 显示项视图的资源编号,loadingres就是等待中的项试图
	public NduoaPageAdapter(Context context,INduoaPageAdapter<T> callback,int pageSize,int res,int loadingRes){
		mContext = context;
		mInflater = LayoutInflater.from(mContext);
		mCallback = callback;
		mPageSize = pageSize;
		mRes = res;
		mLoadingRes = loadingRes;
		mHasLeft=true;
	}
	//必须初始化所需的数据
	public void setInitData(List<T> iniData){
		mResult = iniData;
		mStart+=iniData.size();
                if(iniData.size()<mPageSize){
			mHasLeft = false;
		}
	}
	
	@Override
	public int getCount() {
		return mHasLeft ? mResult.size() + 1 : mResult.size();
	}
	
	@Override
	public Object getItem(int position) {
		return mResult.get(position);
	}
	
	@Override
	public long getItemId(int position) {
		return 0;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if(position == mResult.size()) {
			convertView = mInflater.inflate(mLoadingRes, parent, false);
			new Thread(){
				public void run() {
					List<T> tmps = mCallback.nextPage(mStart, mPageSize);
					if(tmps==null){
						mHasLeft = false;
					}else{
						if(tmps.size()<mPageSize){
							mHasLeft = false;
						}else{
							mHasLeft = true;
						}
						mResult.addAll(tmps);
						mStart+=tmps.size();
					}
					mHandler.sendEmptyMessage(1);
				};
			}.start();
                     convertView.setTag(null);
 		}else {
			if (convertView == null   || convertView.getTag()==null) {
				convertView = mInflater.inflate(mRes,
						parent, false);
			}
			return mCallback.getView(position, convertView, parent, mResult.get(position));
		}
		return convertView;
	}
	
	Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			NduoaPageAdapter.this.notifyDataSetChanged();
		};
	};
	//这里只需要实现这2个接口,就可以保证分页了。第一个函数是当滚动到下一页是,回掉返回获取到的数据。第2个函数
//用来自定义你每项的试图,这个我想不用多说了把。
	public interface INduoaPageAdapter<T>{
		public List<T> nextPage(int start,int size);
		public View getView(int position,View convertView,ViewGroup parent,T value);
	}
}

 

发现出了点小bug 及时为大家修复!

你可能感兴趣的:(android)