ListView上拉加载,下拉刷新

直接粘贴package com.chen.listTongyong;

public interface Pullable
{
	/**
	 * 鍒ゆ柇鏄惁鍙互涓嬫媺锛屽鏋滿?闇?涓嬫媺鍔熻兘鍙互鐩存帴return false
	 *
	 * @return true濡傛灉鍙互涓嬫媺鍚??杩斿洖false
	 */
	boolean canPullDown();

	/**
	 * 鍒ゆ柇鏄惁鍙互涓婃媺锛屽鏋滿?闇?涓婃媺鍔熻兘鍙互鐩存帴return false
	 *
	 * @return true濡傛灉鍙互涓婃媺鍚??杩斿洖false
	 */
	boolean canPullUp();
}

直接贴

 

package com.chen.listTongyong;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ListView;

public class PullableListView extends ListView implements Pullable
{

	public PullableListView(Context context)
	{
		super(context);
	}

	public PullableListView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
	}

	public PullableListView(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
	}

	@Override
	public boolean canPullDown()
	{
		if (getCount() == 0)
		{
			// 娌℃湁item鐨勬椂鍊欎篃鍙互涓嬫媺鍒锋柿
			return true;
		} else if (getFirstVisiblePosition() == 0
				&& getChildAt(0).getTop() >= 0)
		{
			// 婊戝埌ListView鐨勯《閮ㄤ簡
			return true;
		} else
			return false;
	}

	@Override
	public boolean canPullUp()
	{
		if (getCount() == 0)
		{
			// 娌℃湁item鐨勬椂鍊欎篃鍙互涓婃媺鍔犺浿
			return true;
		} else if (getLastVisiblePosition() == (getCount() - 1))
		{
			// 婊戝埌搴曢儴浜?
			if (getChildAt(getLastVisiblePosition() - getFirstVisiblePosition()) != null
					&& getChildAt(
							getLastVisiblePosition()
									- getFirstVisiblePosition()).getBottom() <= getMeasuredHeight())
				return true;
		}
		return false;
	}
}

  直接贴

package com.chen.listTongyong;

import java.util.Timer;
import java.util.TimerTask;

import com.chenke.listview.R;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 鑷畾涔夌殑甯冨眬锛岀敤鏉ョ鐞嗕笁涓瓙鎺т欢锛屽叾涓竴涓槸涓嬫媺澶达紝涓?釜鏄寘鍚唴瀹圭殑pullableView锛堝彲浠ユ槸瀹炵幇Pullable鎺ュ彛鐨勭殑浠讳綍View锛夛紝
 * 杩樻湁涓?釜涓婃媺澶达紝鏇村璇﹁В瑙佸崥瀹ttp://blog.csdn.net/zhongkejingwang/article/details/38868463
 *
 * @author 闄堥潠
 */
public class PullToRefreshLayout extends RelativeLayout
{
	public static final String TAG = "PullToRefreshLayout";
	// 鍒濆鐘舵?
	public static final int INIT = 0;
	// 閲婃斁鍒锋柊
	public static final int RELEASE_TO_REFRESH = 1;
	// 姝e湪鍒锋柊
	public static final int REFRESHING = 2;
	// 閲婃斁鍔犺浇
	public static final int RELEASE_TO_LOAD = 3;
	// 姝e湪鍔犺浇
	public static final int LOADING = 4;
	// 鎿嶄綔瀹屾瘯
	public static final int DONE = 5;
	// 褰撳墠鐘舵?
	private int state = INIT;
	// 鍒锋柊鍥炶皟鎺ュ彛
	private OnRefreshListener mListener;
	// 鍒锋柊鎴愬姛
	public static final int SUCCEED = 0;
	// 鍒锋柊澶辫触
	public static final int FAIL = 1;
	// 鎸変笅Y鍧愭爣锛屼笂涓?釜浜嬩欢鐐筜鍧愭爣
	private float downY, lastY;

	// 涓嬫媺鐨勮窛绂汇?娉ㄦ剰锛歱ullDownY鍜宲ullUpY涓嶅彲鑳藉悓鏃朵笉涓?
	public float pullDownY = 0;
	// 涓婃媺鐨勮窛绂?
	private float pullUpY = 0;

	// 閲婃斁鍒锋柊鐨勮窛绂?
	private float refreshDist = 200;
	// 閲婃斁鍔犺浇鐨勮窛绂?
	private float loadmoreDist = 200;

	private MyTimer timer;
	// 鍥炴粴閫熷害
	public float MOVE_SPEED = 8;
	// 绗竴娆℃墽琛屽竷灞?
	private boolean isLayout = false;
	// 鍦ㄥ埛鏂拌繃绋嬩腑婊戝姩鎿嶄綔
	private boolean isTouch = false;
	// 鎵嬫寚婊戝姩璺濈涓庝笅鎷夊ご鐨勬粦鍔ㄨ窛绂绘瘮锛屼腑闂翠細闅忔鍒囧嚱鏁板彉鍖?
	private float radio = 2;

	// 涓嬫媺绠ご鐨勮浆180掳鍔ㄧ敾
	private RotateAnimation rotateAnimation;
	// 鍧囧寑鏃嬭浆鍔ㄧ敾
	private RotateAnimation refreshingAnimation;

	// 涓嬫媺澶?
	private View refreshView;
	// 涓嬫媺鐨勭澶?
	private View pullView;
	// 姝e湪鍒锋柊鐨勫浘鏍?
	private View refreshingView;
	// 鍒锋柊缁撴灉鍥炬爣
	private View refreshStateImageView;
	// 鍒锋柊缁撴灉锛氭垚鍔熸垨澶辫触
	private TextView refreshStateTextView;

	// 涓婃媺澶?
	private View loadmoreView;
	// 涓婃媺鐨勭澶?
	private View pullUpView;
	// 姝e湪鍔犺浇鐨勫浘鏍?
	private View loadingView;
	// 鍔犺浇缁撴灉鍥炬爣
	private View loadStateImageView;
	// 鍔犺浇缁撴灉锛氭垚鍔熸垨澶辫触
	private TextView loadStateTextView;

	// 瀹炵幇浜哖ullable鎺ュ彛鐨刅iew
	private View pullableView;
	// 杩囨护澶氱偣瑙︾
	private int mEvents;
	// 杩欎袱涓彉閲忕敤鏉ユ帶鍒秔ull鐨勬柟鍚戯紝濡傛灉涓嶅姞鎺у埗锛屽綋鎯呭喌婊¤冻鍙笂鎷夊張鍙笅鎷夋椂娌℃硶涓嬫媺
	private boolean canPullDown = true;
	private boolean canPullUp = true;

	private Context mContext;

	/**
	 * 鎵ц鑷姩鍥炴粴鐨刪andler
	 */
	Handler updateHandler = new Handler()
	{

		@Override
		public void handleMessage(Message msg)
		{
			// 鍥炲脊閫熷害闅忎笅鎷夎窛绂籱oveDeltaY澧炲ぇ鑰屽澶?
			MOVE_SPEED = (float) (8 + 5 * Math.tan(Math.PI / 2
					/ getMeasuredHeight() * (pullDownY + Math.abs(pullUpY))));
			if (!isTouch)
			{
				// 姝e湪鍒锋柊锛屼笖娌℃湁寰?笂鎺ㄧ殑璇濆垯鎮仠锛屾樉绀?姝e湪鍒锋柊..."
				if (state == REFRESHING && pullDownY <= refreshDist)
				{
					pullDownY = refreshDist;
					timer.cancel();
				} else if (state == LOADING && -pullUpY <= loadmoreDist)
				{
					pullUpY = -loadmoreDist;
					timer.cancel();
				}

			}
			if (pullDownY > 0)
				pullDownY -= MOVE_SPEED;
			else if (pullUpY < 0)
				pullUpY += MOVE_SPEED;
			if (pullDownY < 0)
			{
				// 宸插畬鎴愬洖寮?
				pullDownY = 0;
				pullView.clearAnimation();
				// 闅愯棌涓嬫媺澶存椂鏈夊彲鑳借繕鍦ㄥ埛鏂帮紝鍙湁褰撳墠鐘舵?涓嶆槸姝e湪鍒锋柊鏃舵墠鏀瑰彉鐘舵?
				if (state != REFRESHING && state != LOADING)
					changeState(INIT);
				timer.cancel();
				requestLayout();
			}
			if (pullUpY > 0)
			{
				// 宸插畬鎴愬洖寮?
				pullUpY = 0;
				pullUpView.clearAnimation();
				// 闅愯棌涓婃媺澶存椂鏈夊彲鑳借繕鍦ㄥ埛鏂帮紝鍙湁褰撳墠鐘舵?涓嶆槸姝e湪鍒锋柊鏃舵墠鏀瑰彉鐘舵?
				if (state != REFRESHING && state != LOADING)
					changeState(INIT);
				timer.cancel();
				requestLayout();
			}
			Log.d("handle", "handle");
			// 鍒锋柊甯冨眬,浼氳嚜鍔ㄨ皟鐢╫nLayout
			requestLayout();
			// 娌℃湁鎷栨媺鎴栬?鍥炲脊瀹屾垚
			if (pullDownY + Math.abs(pullUpY) == 0)
				timer.cancel();
		}

	};

	public void setOnRefreshListener(OnRefreshListener listener)
	{
		mListener = listener;
	}

	public PullToRefreshLayout(Context context)
	{
		super(context);
		initView(context);
	}

	public PullToRefreshLayout(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		initView(context);
	}

	public PullToRefreshLayout(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
		initView(context);
	}

	private void initView(Context context)
	{
		mContext = context;
		timer = new MyTimer(updateHandler);
		rotateAnimation = (RotateAnimation) AnimationUtils.loadAnimation(
				context, R.anim.reverse_anim);
		refreshingAnimation = (RotateAnimation) AnimationUtils.loadAnimation(
				context, R.anim.rotating);
		// 娣诲姞鍖??杞姩鍔ㄧ敾
		LinearInterpolator lir = new LinearInterpolator();
		rotateAnimation.setInterpolator(lir);
		refreshingAnimation.setInterpolator(lir);
	}

	private void hide()
	{
		timer.schedule(5);
	}

	/**
	 * 瀹屾垚鍒锋柊鎿嶄綔锛屾樉绀哄埛鏂扮粨鏋溿?娉ㄦ剰锛氬埛鏂板畬鎴愬悗涓?畾瑕佽皟鐢ㄨ繖涓柟娉?
	 */
	/**
	 * @param refreshResult
	 *            PullToRefreshLayout.SUCCEED浠h〃鎴愬姛锛孭ullToRefreshLayout.FAIL浠h〃澶辫触
	 */
	public void refreshFinish(int refreshResult)
	{
		refreshingView.clearAnimation();
		refreshingView.setVisibility(View.GONE);
		switch (refreshResult)
		{
		case SUCCEED:
			// 鍒锋柊鎴愬姛
			refreshStateImageView.setVisibility(View.VISIBLE);
			refreshStateTextView.setText(R.string.refresh_succeed);
			refreshStateImageView
					.setBackgroundResource(R.drawable.refresh_succeed);
			break;
		case FAIL:
		default:
			// 鍒锋柊澶辫触
			refreshStateImageView.setVisibility(View.VISIBLE);
			refreshStateTextView.setText(R.string.refresh_fail);
			refreshStateImageView
					.setBackgroundResource(R.drawable.refresh_failed);
			break;
		}
		if (pullDownY > 0)
		{
			// 鍒锋柊缁撴灉鍋滅暀1绉?
			new Handler()
			{
				@Override
				public void handleMessage(Message msg)
				{
					changeState(DONE);
					hide();
				}
			}.sendEmptyMessageDelayed(0, 1000);
		} else
		{
			changeState(DONE);
			hide();
		}
	}

	/**
	 * 鍔犺浇瀹屾瘯锛屾樉绀哄姞杞界粨鏋溿?娉ㄦ剰锛氬姞杞藉畬鎴愬悗涓?畾瑕佽皟鐢ㄨ繖涓柟娉?
	 *
	 * @param refreshResult
	 *            PullToRefreshLayout.SUCCEED浠h〃鎴愬姛锛孭ullToRefreshLayout.FAIL浠h〃澶辫触
	 */
	public void loadmoreFinish(int refreshResult)
	{
		loadingView.clearAnimation();
		loadingView.setVisibility(View.GONE);
		switch (refreshResult)
		{
		case SUCCEED:
			// 鍔犺浇鎴愬姛
			loadStateImageView.setVisibility(View.VISIBLE);
			loadStateTextView.setText(R.string.load_succeed);
			loadStateImageView.setBackgroundResource(R.drawable.load_succeed);
			break;
		case FAIL:
		default:
			// 鍔犺浇澶辫触
			loadStateImageView.setVisibility(View.VISIBLE);
			loadStateTextView.setText(R.string.load_fail);
			loadStateImageView.setBackgroundResource(R.drawable.load_failed);
			break;
		}
		if (pullUpY < 0)
		{
			// 鍒锋柊缁撴灉鍋滅暀1绉?
			new Handler()
			{
				@Override
				public void handleMessage(Message msg)
				{
					changeState(DONE);
					hide();
				}
			}.sendEmptyMessageDelayed(0, 1000);
		} else
		{
			changeState(DONE);
			hide();
		}
	}

	private void changeState(int to)
	{
		state = to;
		switch (state)
		{
		case INIT:
			// 涓嬫媺甯冨眬鍒濆鐘舵?
			refreshStateImageView.setVisibility(View.GONE);
			refreshStateTextView.setText(R.string.pull_to_refresh);
			pullView.clearAnimation();
			pullView.setVisibility(View.VISIBLE);
			// 涓婃媺甯冨眬鍒濆鐘舵?
			loadStateImageView.setVisibility(View.GONE);
			loadStateTextView.setText(R.string.pullup_to_load);
			pullUpView.clearAnimation();
			pullUpView.setVisibility(View.VISIBLE);
			break;
		case RELEASE_TO_REFRESH:
			// 閲婃斁鍒锋柊鐘舵?
			refreshStateTextView.setText(R.string.release_to_refresh);
			pullView.startAnimation(rotateAnimation);
			break;
		case REFRESHING:
			// 姝e湪鍒锋柊鐘舵?
			pullView.clearAnimation();
			refreshingView.setVisibility(View.VISIBLE);
			pullView.setVisibility(View.INVISIBLE);
			refreshingView.startAnimation(refreshingAnimation);
			refreshStateTextView.setText(R.string.refreshing);
			break;
		case RELEASE_TO_LOAD:
			// 閲婃斁鍔犺浇鐘舵?
			loadStateTextView.setText(R.string.release_to_load);
			pullUpView.startAnimation(rotateAnimation);
			break;
		case LOADING:
			// 姝e湪鍔犺浇鐘舵?
			pullUpView.clearAnimation();
			loadingView.setVisibility(View.VISIBLE);
			pullUpView.setVisibility(View.INVISIBLE);
			loadingView.startAnimation(refreshingAnimation);
			loadStateTextView.setText(R.string.loading);
			break;
		case DONE:
			// 鍒锋柊鎴栧姞杞藉畬姣曪紝鍟ラ兘涓嶅仛
			break;
		}
	}

	/**
	 * 涓嶉檺鍒朵笂鎷夋垨涓嬫媺
	 */
	private void releasePull()
	{
		canPullDown = true;
		canPullUp = true;
	}

	/*
	 * 锛堥潪 Javadoc锛夌敱鐖舵帶浠跺喅瀹氭槸鍚﹀垎鍙戜簨浠讹紝闃叉浜嬩欢鍐茬獊
	 *
	 * @see android.view.ViewGroup#dispatchTouchEvent(android.view.MotionEvent)
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev)
	{
		switch (ev.getActionMasked())
		{
		case MotionEvent.ACTION_DOWN:
			downY = ev.getY();
			lastY = downY;
			timer.cancel();
			mEvents = 0;
			releasePull();
			break;
		case MotionEvent.ACTION_POINTER_DOWN:
		case MotionEvent.ACTION_POINTER_UP:
			// 杩囨护澶氱偣瑙︾
			mEvents = -1;
			break;
		case MotionEvent.ACTION_MOVE:
			if (mEvents == 0)
			{
				if (pullDownY > 0
						|| (((Pullable) pullableView).canPullDown()
								&& canPullDown && state != LOADING))
				{
					// 鍙互涓嬫媺锛屾鍦ㄥ姞杞芥椂涓嶈兘涓嬫媺
					// 瀵瑰疄闄呮粦鍔ㄨ窛绂诲仛缂╁皬锛岄?鎴愮敤鍔涙媺鐨勬劅瑙?
					pullDownY = pullDownY + (ev.getY() - lastY) / radio;
					if (pullDownY < 0)
					{
						pullDownY = 0;
						canPullDown = false;
						canPullUp = true;
					}
					if (pullDownY > getMeasuredHeight())
						pullDownY = getMeasuredHeight();
					if (state == REFRESHING)
					{
						// 姝e湪鍒锋柊鐨勬椂鍊欒Е鎽哥Щ鍔?
						isTouch = true;
					}
				} else if (pullUpY < 0
						|| (((Pullable) pullableView).canPullUp() && canPullUp && state != REFRESHING))
				{
					// 鍙互涓婃媺锛屾鍦ㄥ埛鏂版椂涓嶈兘涓婃媺
					pullUpY = pullUpY + (ev.getY() - lastY) / radio;
					if (pullUpY > 0)
					{
						pullUpY = 0;
						canPullDown = true;
						canPullUp = false;
					}
					if (pullUpY < -getMeasuredHeight())
						pullUpY = -getMeasuredHeight();
					if (state == LOADING)
					{
						// 姝e湪鍔犺浇鐨勬椂鍊欒Е鎽哥Щ鍔?
						isTouch = true;
					}
				} else
					releasePull();
			} else
				mEvents = 0;
			lastY = ev.getY();
			// 鏍规嵁涓嬫媺璺濈鏀瑰彉姣斾緥
			radio = (float) (2 + 2 * Math.tan(Math.PI / 2 / getMeasuredHeight()
					* (pullDownY + Math.abs(pullUpY))));
			if (pullDownY > 0 || pullUpY < 0)
				requestLayout();
			if (pullDownY > 0)
			{
				if (pullDownY <= refreshDist
						&& (state == RELEASE_TO_REFRESH || state == DONE))
				{
					// 濡傛灉涓嬫媺璺濈娌¤揪鍒板埛鏂扮殑璺濈涓斿綋鍓嶇姸鎬佹槸閲婃斁鍒锋柊锛屾敼鍙樼姸鎬佷负涓嬫媺鍒锋柊
					changeState(INIT);
				}
				if (pullDownY >= refreshDist && state == INIT)
				{
					// 濡傛灉涓嬫媺璺濈杈惧埌鍒锋柊鐨勮窛绂讳笖褰撳墠鐘舵?鏄垵濮嬬姸鎬佸埛鏂帮紝鏀瑰彉鐘舵?涓洪噴鏀惧埛鏂?
					changeState(RELEASE_TO_REFRESH);
				}
			} else if (pullUpY < 0)
			{
				// 涓嬮潰鏄垽鏂笂鎷夊姞杞界殑锛屽悓涓婏紝娉ㄦ剰pullUpY鏄礋鍊?
				if (-pullUpY <= loadmoreDist
						&& (state == RELEASE_TO_LOAD || state == DONE))
				{
					changeState(INIT);
				}
				// 涓婃媺鎿嶄綔
				if (-pullUpY >= loadmoreDist && state == INIT)
				{
					changeState(RELEASE_TO_LOAD);
				}

			}
			// 鍥犱负鍒锋柊鍜屽姞杞芥搷浣滀笉鑳藉悓鏃惰繘琛岋紝鎵?互pullDownY鍜宲ullUpY涓嶄細鍚屾椂涓嶄负0锛屽洜姝よ繖閲岀敤(pullDownY +
			// Math.abs(pullUpY))灏卞彲浠ヤ笉瀵瑰綋鍓嶇姸鎬佷綔鍖哄垎浜?
			if ((pullDownY + Math.abs(pullUpY)) > 8)
			{
				// 闃叉涓嬫媺杩囩▼涓瑙﹀彂闀挎寜浜嬩欢鍜岀偣鍑讳簨浠?
				ev.setAction(MotionEvent.ACTION_CANCEL);
			}
			break;
		case MotionEvent.ACTION_UP:
			if (pullDownY > refreshDist || -pullUpY > loadmoreDist)
			// 姝e湪鍒锋柊鏃跺線涓嬫媺锛堟鍦ㄥ姞杞芥椂寰?笂鎷夛級锛岄噴鏀惧悗涓嬫媺澶达紙涓婃媺澶达級涓嶉殣钘?
			{
				isTouch = false;
			}
			if (state == RELEASE_TO_REFRESH)
			{
				changeState(REFRESHING);
				// 鍒锋柊鎿嶄綔
				if (mListener != null)
					mListener.onRefresh(this);
			} else if (state == RELEASE_TO_LOAD)
			{
				changeState(LOADING);
				// 鍔犺浇鎿嶄綔
				if (mListener != null)
					mListener.onLoadMore(this);
			}
			hide();
		default:
			break;
		}
		// 浜嬩欢鍒嗗彂浜ょ粰鐖剁被
		super.dispatchTouchEvent(ev);
		return true;
	}

	/**
	 * @author chenjing 鑷姩妯℃嫙鎵嬫寚婊戝姩鐨則ask
	 *
	 */
	private class AutoRefreshAndLoadTask extends
			AsyncTask<Integer, Float, String>
	{

		@Override
		protected String doInBackground(Integer... params)
		{
			while (pullDownY < 4 / 3 * refreshDist)
			{
				pullDownY += MOVE_SPEED;
				publishProgress(pullDownY);
				try
				{
					Thread.sleep(params[0]);
				} catch (InterruptedException e)
				{
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result)
		{
			changeState(REFRESHING);
			// 鍒锋柊鎿嶄綔
			if (mListener != null)
				mListener.onRefresh(PullToRefreshLayout.this);
			hide();
		}

		@Override
		protected void onProgressUpdate(Float... values)
		{
			if (pullDownY > refreshDist)
				changeState(RELEASE_TO_REFRESH);
			requestLayout();
		}

	}

	/**
	 * 鑷姩鍒锋柊
	 */
	public void autoRefresh()
	{
		AutoRefreshAndLoadTask task = new AutoRefreshAndLoadTask();
		task.execute(20);
	}

	/**
	 * 鑷姩鍔犺浇
	 */
	public void autoLoad()
	{
		pullUpY = -loadmoreDist;
		requestLayout();
		changeState(LOADING);
		// 鍔犺浇鎿嶄綔
		if (mListener != null)
			mListener.onLoadMore(this);
	}

	private void initView()
	{
		// 鍒濆鍖栦笅鎷夊竷灞?
		pullView = refreshView.findViewById(R.id.pull_icon);
		refreshStateTextView = (TextView) refreshView
				.findViewById(R.id.state_tv);
		refreshingView = refreshView.findViewById(R.id.refreshing_icon);
		refreshStateImageView = refreshView.findViewById(R.id.state_iv);
		// 鍒濆鍖栦笂鎷夊竷灞?
		pullUpView = loadmoreView.findViewById(R.id.pullup_icon);
		loadStateTextView = (TextView) loadmoreView
				.findViewById(R.id.loadstate_tv);
		loadingView = loadmoreView.findViewById(R.id.loading_icon);
		loadStateImageView = loadmoreView.findViewById(R.id.loadstate_iv);
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b)
	{
		Log.d("Test", "Test");
		if (!isLayout)
		{
			// 杩欓噷鏄涓?杩涙潵鐨勬椂鍊欏仛涓?簺鍒濆鍖?
			refreshView = getChildAt(0);
			pullableView = getChildAt(1);
			loadmoreView = getChildAt(2);
			isLayout = true;
			initView();
			refreshDist = ((ViewGroup) refreshView).getChildAt(0)
					.getMeasuredHeight();
			loadmoreDist = ((ViewGroup) loadmoreView).getChildAt(0)
					.getMeasuredHeight();
		}
		// 鏀瑰彉瀛愭帶浠剁殑甯冨眬锛岃繖閲岀洿鎺ョ敤(pullDownY + pullUpY)浣滀负鍋忕Щ閲忥紝杩欐牱灏卞彲浠ヤ笉瀵瑰綋鍓嶇姸鎬佷綔鍖哄垎
		refreshView.layout(0,
				(int) (pullDownY + pullUpY) - refreshView.getMeasuredHeight(),
				refreshView.getMeasuredWidth(), (int) (pullDownY + pullUpY));
		pullableView.layout(0, (int) (pullDownY + pullUpY),
				pullableView.getMeasuredWidth(), (int) (pullDownY + pullUpY)
						+ pullableView.getMeasuredHeight());
		loadmoreView.layout(0,
				(int) (pullDownY + pullUpY) + pullableView.getMeasuredHeight(),
				loadmoreView.getMeasuredWidth(),
				(int) (pullDownY + pullUpY) + pullableView.getMeasuredHeight()
						+ loadmoreView.getMeasuredHeight());
	}

	class MyTimer
	{
		private Handler handler;
		private Timer timer;
		private MyTask mTask;

		public MyTimer(Handler handler)
		{
			this.handler = handler;
			timer = new Timer();
		}

		public void schedule(long period)
		{
			if (mTask != null)
			{
				mTask.cancel();
				mTask = null;
			}
			mTask = new MyTask(handler);
			timer.schedule(mTask, 0, period);
		}

		public void cancel()
		{
			if (mTask != null)
			{
				mTask.cancel();
				mTask = null;
			}
		}

		class MyTask extends TimerTask
		{
			private Handler handler;

			public MyTask(Handler handler)
			{
				this.handler = handler;
			}

			@Override
			public void run()
			{
				handler.obtainMessage().sendToTarget();
			}

		}
	}

	/**
	 * 鍒锋柊鍔犺浇鍥炶皟鎺ュ彛
	 *
	 * @author chenjing
	 *
	 */
	public interface OnRefreshListener
	{
		/**
		 * 鍒锋柊鎿嶄綔
		 */
		void onRefresh(PullToRefreshLayout pullToRefreshLayout);

		/**
		 * 鍔犺浇鎿嶄綔
		 */
		void onLoadMore(PullToRefreshLayout pullToRefreshLayout);

	}

}

  适配器

package com.chenke.listview.adapter;

import java.util.List;

import com.chenke.listview.R;
import com.chenke.listview.vo.Mydata;
import com.lidroid.xutils.BitmapUtils;

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

public class Base extends BaseAdapter{
	//定义变量
	Context con;
	List<Mydata> list;
	//构造方法
	public Base(Context con, List<Mydata> list) {
		super();
		this.con = con;
		this.list = list;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int arg0, View arg1, ViewGroup arg2) {
		// 定义变量
		View v=null;
		ViewHolder vh;
		if (arg1==null) {
			v=View.inflate(con, R.layout.base, null);
			vh=new ViewHolder();
			//找到所需控件
			vh.iv=(ImageView) v.findViewById(R.id.iv);
			vh.tv=(TextView) v.findViewById(R.id.tv);
			//绑定
			v.setTag(vh);
		}else{
			v=arg1;
			//解绑
			vh=(ViewHolder) v.getTag();
		}
		//创建bitmap对象
		BitmapUtils bu=new BitmapUtils(con);
		//为控件赋值
		bu.display(vh.iv, list.get(arg0).getPic_url());
		vh.tv.setText(list.get(arg0).getNews_title());
		return v;
	}
	//定义持有类
	class ViewHolder{
		TextView tv;
		ImageView iv;
	}
	public void updateadapter() {
		this.list=list;
		this.notifyDataSetChanged();

	}

}

  主方法

package com.chenke.listview;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.http.client.ClientProtocolException;

import com.chen.listTongyong.PullToRefreshLayout;
import com.chen.listTongyong.PullableListView;
import com.chen.listTongyong.PullToRefreshLayout.OnRefreshListener;
import com.chenke.listview.adapter.Base;
import com.chenke.listview.httpget.MyHttpGet;
import com.chenke.listview.vo.MySupper;
import com.chenke.listview.vo.Mydata;
import com.google.gson.Gson;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Window;

public class MainActivity extends Activity {

	int page = 1;
	Handler ha = new Handler() {

		public void handleMessage(Message msg) {

			String ma = msg.obj.toString();
			Gson gs = new Gson();
			lis = new ArrayList<Mydata>();
			MySupper fromJson = gs.fromJson(ma, MySupper.class);

			list = fromJson.getData();

			if (xialist != null) {
				lis.addAll(xialist);
				lis.addAll(list);
			}

			Base ba = new Base(MainActivity.this, lis);
			lv.setAdapter(ba);
		};
	};

	private Base ba;
	private PullableListView lv;

	private List<Mydata> list;

	private List<Mydata> xialist;
	private List<Mydata> lis;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置隐藏标题
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 加载xml文件
		setContentView(R.layout.activity_main);

		lv = (PullableListView) findViewById(R.id.list);
		PullToRefreshLayout layout = (PullToRefreshLayout) findViewById(R.id.layout);

		layout.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {
				ha.postDelayed(new Runnable() {

					@Override
					public void run() {

						list.addAll(0, shangdata());
						// 千万别忘了告诉控件刷新完毕了哦!

						updata();
						// 千万别忘了告诉控件加载完毕了哦!
						pullToRefreshLayout
								.loadmoreFinish(PullToRefreshLayout.SUCCEED);
					}

				}, 2000);

			}

			@Override
			public void onLoadMore(final PullToRefreshLayout pullToRefreshLayout) {
				ha.postDelayed(new Runnable() {

					@Override
					public void run() {
						updata();
						list.addAll(xiadata());
						// 千万别忘了告诉控件加载完毕了哦!
						pullToRefreshLayout
								.loadmoreFinish(PullToRefreshLayout.SUCCEED);
					}
				}, 2000);

			}
		});
		new Thread() {
			public void run() {
				try {
					String str = MyHttpGet
							.getjson("http://api.expoon.com/AppNews/getNewsList/type/1/p/"
									+ page);
					ha.sendMessage(ha.obtainMessage(1, str));

				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
	}

	public void updata() {
		if (ba == null) {
			ba = new Base(MainActivity.this, lis);
			// 为lv添加适配器
			lv.setAdapter(ba);
		} else {
			ba.updateadapter();
		}
	}

	public List<Mydata> shangdata() {
		List<Mydata> shanglist = new ArrayList<Mydata>();
		// 向集合中添加数据

		for (int j = 0; j < 2; j++) {

			new Thread() {
				public void run() {
					page = 1;
					System.out.println(page + "0000000000000000");
					String str;
					try {
						str = MyHttpGet
								.getjson("http://api.expoon.com/AppNews/getNewsList/type/1/p/"
										+ page);
						ha.sendMessage(ha.obtainMessage(1, str));
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				};
			}.start();

		}

		return shanglist;
	}

	public List<Mydata> xiadata() {
		xialist = new ArrayList<Mydata>();

		// 向集合中添加数据
		for (int j = 0; j < 3; j++) {
			page++;
			System.out.println(page);
			new Thread() {
				public void run() {
					String str;
					try {
						str = MyHttpGet
								.getjson("http://api.expoon.com/AppNews/getNewsList/type/1/p/"
										+ page);
						ha.sendMessage(ha.obtainMessage(1, str));
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				};
			}.start();

		}
		return xialist;
	}

}

  直接贴

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/loadmore_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/gray" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:paddingBottom="20dp"
        android:paddingTop="20dp" >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true" >

            <ImageView
                android:id="@+id/pullup_icon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="60dp"
                android:background="@drawable/pullup_icon_big" />

            <ImageView
                android:id="@+id/loading_icon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="60dp"
                android:background="@drawable/loading"
                android:visibility="gone" />

            <TextView
                android:id="@+id/loadstate_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="@string/pullup_to_load"
                android:textColor="@color/black"
                android:textSize="16sp" />

            <ImageView
                android:id="@+id/loadstate_iv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginRight="8dp"
                android:layout_toLeftOf="@id/loadstate_tv"
                android:visibility="gone" />
        </RelativeLayout>
    </RelativeLayout>

</RelativeLayout>

  

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/head_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/light_blue" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:paddingBottom="20dp"
        android:paddingTop="20dp" >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true" >

            <ImageView
                android:id="@+id/pull_icon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="60dp"
                android:background="@drawable/pull_icon_big" />

            <ImageView
                android:id="@+id/refreshing_icon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="60dp"
                android:background="@drawable/refreshing"
                android:visibility="gone" />

            <TextView
                android:id="@+id/state_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="@string/pull_to_refresh"
                android:textColor="@color/white"
                android:textSize="16sp" />

            <ImageView
                android:id="@+id/state_iv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginRight="8dp"
                android:layout_toLeftOf="@id/state_tv"
                android:visibility="gone" />
        </RelativeLayout>
    </RelativeLayout>

</RelativeLayout>

  Values 里的String类

  <string name="app_name">ListView网络上拉下拉</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="head">这里是HeadView</string>
    <string name="pull_to_refresh">下拉刷新</string>
    <string name="release_to_refresh">释放立即刷新</string>
    <string name="refreshing">正在刷新...</string>
    <string name="refresh_succeed">刷新成功</string>
    <string name="refresh_fail">刷新失败</string>
    <string name="pullup_to_load">上拉加载更多</string>
    <string name="release_to_load">释放立即加载</string>
    <string name="loading">正在加载...</string>
    <string name="load_succeed">加载成功</string>
    <string name="load_fail">加载失败</string>

  Values里的color

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="white">#FFFFFF</color>
    <color name="black">#000000</color>
    <color name="gray">#aaaaaa</color>
    <color name="light_blue">#6593cb</color>
</resources>

  直接贴

reverse_anim.xml

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="100"
    android:fillAfter="true"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="0"
    android:toDegrees="180" >

</rotate>

 直接贴

rotating.xml

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1500"
    android:fillAfter="true"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="-1"
    android:toDegrees="360" >

</rotate>

  

  需要一张图片,做为箭头

时间: 2024-10-21 22:19:39

ListView上拉加载,下拉刷新的相关文章

ListView上拉加载下拉刷新

主要用到了这个几个文件,MainActivity是界面的Activity,MyAdapter是ListView的自定义适配,MyListView是自定义带头部LIistView,如果只需要上拉加载就不需要:activity_main.xml是住界面,item.xml是ListView的子布局里面只有一个TextView,listview_footer.xml是listview的加载更多的底部布局,listview_header.xml是listview的头部布局. MainActivity.ja

XML解析及上拉加载下拉刷新

XML解析及上拉加载下拉刷新 1.XML格式 2.GData和XPath遍历 //配置XML库(配置完才能使用) //(1)添加头文件搜索路径 // Header Search Paths-> /usr/include/libxml2 //(2)添加二进制库 // Link library -> lixml2.dylib //(3)源文件添加编译选项 // -fno-objc-arc //(4)添加头文件 // #import "GDataXMLNode.h"*/ XPat

使用dragloader.js插件实现上拉加载/下拉刷新..

在写代码时候有个需求是,在触屏页面,为了加快页面加载速度,案件列表每页展示5条数据: 然后点击更多,展示下一页数据: 但是为了触屏更好的体验,改为往上滑动案件列表,加载下一页数据:就是要实现上拉加载/下拉刷新的效果: 我只用到了 上拉加载: 参考资料:http://blog.csdn.net/xb12369/article/details/39202711 下面是写的demo: html代码: <!DOCTYPE html> <html lang="en"> &

Mint-ui中loadmore(上拉加载下拉刷新)组件在ios中滑动会触发点击事件的解决方法

bug说明: Mint-ui中loadmore(上拉加载下拉刷新)组件 在 使用fastclick的情况下 ,在ios设备中滑动会触发点击事件: 解决方法: 我是按需引入,去项目中找到loadmore下的index.js,全部引入的要找mint下面mint-ui.common.js 路径如下:你的项目名/node_modules\mint-ui\lib\loadmore\index.js 搜索 handleTouchEnd ,记得写event进去 handleTouchEnd: function

微信小程序上拉加载下拉刷新

微信小程序实现上拉加载下拉刷新 使用小程序默认提供方法. (1). 在xxx.json 中开启下拉刷新,需要设置backgroundColor,或者是backgroundTextStyle ,因为加载的动画可能会是白色背景,会看不清. { "usingComponents": { "annicate": "/components/annicate/index" }, "navigationBarTitleText": &quo

移动端上拉加载下拉刷新

<template> <div class="wrapper" ref="wrapper"> <div class="content" > <div class="refresh" :class="{ativeRefresh:refresh}">刷新</div> <div class="ct-row" v-for=&quo

【PullToRefresh 系列一】 Android上拉加载下拉刷新控件详解

转载请注明:http://blog.csdn.net/duguang77/article/details/40921601 作者信息: PullToRefresh控件下载地址:https://github.com/chrisbanes/Android-PullToRefresh 作者:https://github.com/chrisbanes 百度网盘下载地址:http://pan.baidu.com/s/1o6umifw (一)导入方法: 1.下载后将extras,library,sample

xlistview上拉加载 下拉刷新

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent" >

XListView实现上拉加载下拉刷新

package com.loaderman.androiddemo; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.view.animation

上拉加载下拉刷新控件WaterRefreshLoadMoreView

效果: 源码: // // SRSlimeView // @author SR // Modified by JunHan on 13-9-18. // #import <UIKit/UIKit.h> #define kStartTo 0.7f #define kEndTo 0.15f #define kAnimationInterval (1.0f / 50.0f) NS_INLINE CGFloat distansBetween(CGPoint p1 , CGPoint p2) { ret