Xlistview刷新

1、在自己的项目中按以往的方法写listview、grilview的布局、适配器、以及界面显示内容
2、在项目中引入第三方类库(这里以listview为例)
3、建议为该类库单独建立一个包。
4、导入如图所示的类到自己的项目中:

5、导入如图所示的类到自己的项目中,注:标号1必倒,
      标号2,当我们是listview时为pullableListView;
                  当我们是gridview时为pullablegridview,以此类推

6、导入drawable下的内容:

7、导入anim下的文件

8、导入values下的文件,注:需要将strings.xml下的除第一条外的文件复制到自己的string.xml文件中
        

9、导入layout下的最后两个文件

10、至此需要导入的类库完毕,打开报错的代码,进行改正(change、更改R包);
11、修改xml中的文件,如图

12、mainactivty的java代码中的修改
public class MainActivity extends Activity {

    int page = 1;
    private PullableListView lv;
    private Base ba;
    private List<Mydata> list = new ArrayList<Mydata>();
    private String url = "http://api.expoon.com/AppNews/getNewsList/type/1/p/";
    // 创建handler对象
    Handler h = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String result = msg.obj.toString();
            Gson g = new Gson();
            MySupper ms = g.fromJson(result, MySupper.class);
            ArrayList<Mydata> data = ms.getData();
            if (page==1) {
                list.clear();
            }
            Log.e("111111111111", "11111111111111111111111111111");
            list.addAll(data);
            update();

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 设置隐藏标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 加载xml文件
        setContentView(R.layout.activity_main);
        PullToRefreshLayout layout = (PullToRefreshLayout) findViewById(R.id.layout);
        lv = (PullableListView) findViewById(R.id.list);
        setJson();
        layout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {

                h.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page = 1;
                        setJson();
                        // 千万别忘了告诉控件刷新完毕了哦!
                        pullToRefreshLayout
                                .refreshFinish(PullToRefreshLayout.SUCCEED);
                    }

                }, 1000);

            }

            @Override
            public void onLoadMore(final PullToRefreshLayout pullToRefreshLayout) {

                h.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        page++;
                        setJson();
                        // 千万别忘了告诉控件加载完毕了哦!
                        pullToRefreshLayout
                                .loadmoreFinish(PullToRefreshLayout.SUCCEED);

                    }
                }, 1000);
            }
        });

    }

    public void setJson() {

        new Thread() {
            public void run() {
                try {
                    String string = MyHttpGet.getjson(url, page);
                    Message message = h.obtainMessage();
                    message.obj = string;
                    h.sendMessage(message);
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();

    }

    // 创建更新适配器的方法
    public void update() {
        // 判断ba是否为空
        if (ba == null) {
            ba = new Base(MainActivity.this, list);
            // 为lv添加适配器
            lv.setAdapter(ba);
        } else {
            // 刷新适配器
            ba.UpDataAdapter(list);
        }
    }

}
13、适配器要写刷新适配器的方法
//定义更新适配器的方法
    public void UpDataAdapter(List<Mydata> list){
        this.list=list;
        this.notifyDataSetChanged();
    }
14、如果页面是用fragment填充的viewpager,则在viewpager页面加载布局前写一个判断,以防止fragmen被销毁而导致的数据加载不出来:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // 填充布局
        if (v==null) {
            v = View.inflate(getActivity(), R.layout.tuijian, null);
            layout = (PullToRefreshLayout) v
            .findViewById(R.id.layout);

        }
        ViewGroup mParent = (ViewGroup) v.getParent();

        if(mParent!=null){
            mParent.removeView(v);
        }

        lv = (PullableListView) v.findViewById(R.id.listview);

 Pullable.java; 

,直接沾
package com.jingchen.pulltorefresh.pullableview;

public interface Pullable
{
	/**
	 * 判断是否可以下拉,如果不需要下拉功能可以直接return false
	 *
	 * @return true如果可以下拉否则返回false
	 */
	boolean canPullDown();

	/**
	 * 判断是否可以上拉,如果不需要上拉功能可以直接return false
	 *
	 * @return true如果可以上拉否则返回false
	 */
	boolean canPullUp();
}

  PullableListView.java

,直接沾

package com.jingchen.pulltorefresh.pullableview;

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;
}
}

  

PullToRefreshLayout.java ,直接沾
package com.jingchen.pulltorefresh;

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

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;

import com.jingchen.pulltorefresh.pullableview.Pullable;

/**
 * 自定义的布局,用来管理三个子控件,其中一个是下拉头,一个是包含内容的pullableView(可以是实现Pullable接口的的任何View),
 * 还有一个上拉头,更多详解见博客http://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;
	// 正在刷新
	public static final int REFRESHING = 2;
	// 释放加载
	public static final int RELEASE_TO_LOAD = 3;
	// 正在加载
	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坐标,上一个事件点Y坐标
	private float downY, lastY;

	// 下拉的距离。注意:pullDownY和pullUpY不可能同时不为0
	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;
	// 正在刷新的图标
	private View refreshingView;
	// 刷新结果图标
	private View refreshStateImageView;
	// 刷新结果:成功或失败
	private TextView refreshStateTextView;

	// 上拉头
	private View loadmoreView;
	// 上拉的箭头
	private View pullUpView;
	// 正在加载的图标
	private View loadingView;
	// 加载结果图标
	private View loadStateImageView;
	// 加载结果:成功或失败
	private TextView loadStateTextView;

	// 实现了Pullable接口的View
	private View pullableView;
	// 过滤多点触碰
	private int mEvents;
	// 这两个变量用来控制pull的方向,如果不加控制,当情况满足可上拉又可下拉时没法下拉
	private boolean canPullDown = true;
	private boolean canPullUp = true;

	private Context mContext;

	/**
	 * 执行自动回滚的handler
	 */
	Handler updateHandler = new Handler()
	{

		@Override
		public void handleMessage(Message msg)
		{
			// 回弹速度随下拉距离moveDeltaY增大而增大
			MOVE_SPEED = (float) (8 + 5 * Math.tan(Math.PI / 2
					/ getMeasuredHeight() * (pullDownY + Math.abs(pullUpY))));
			if (!isTouch)
			{
				// 正在刷新,且没有往上推的话则悬停,显示"正在刷新..."
				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();
				// 隐藏下拉头时有可能还在刷新,只有当前状态不是正在刷新时才改变状态
				if (state != REFRESHING && state != LOADING)
					changeState(INIT);
				timer.cancel();
				requestLayout();
			}
			if (pullUpY > 0)
			{
				// 已完成回弹
				pullUpY = 0;
				pullUpView.clearAnimation();
				// 隐藏上拉头时有可能还在刷新,只有当前状态不是正在刷新时才改变状态
				if (state != REFRESHING && state != LOADING)
					changeState(INIT);
				timer.cancel();
				requestLayout();
			}
			Log.d("handle", "handle");
			// 刷新布局,会自动调用onLayout
			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代表成功,PullToRefreshLayout.FAIL代表失败
	 */
	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代表成功,PullToRefreshLayout.FAIL代表失败
	 */
	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:
			// 正在刷新状态
			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:
			// 正在加载状态
			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)
					{
						// 正在刷新的时候触摸移动
						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)
					{
						// 正在加载的时候触摸移动
						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和pullUpY不会同时不为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)
			// 正在刷新时往下拉(正在加载时往上拉),释放后下拉头(上拉头)不隐藏
			{
				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 自动模拟手指滑动的task
	 *
	 */
	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);
	}

}

  anima下的两个文件

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>

  load_more.xml

<?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>

  refresh_head.xml

<?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>

  color.xml

<?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>

 Values 下的

  <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>

  

 

时间: 2024-10-14 19:07:53

Xlistview刷新的相关文章

xlistview刷新加载

package com.example.fragment; import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.List; import com.example.adapter.MybaseAdatpter;import com.example.jinritoutiao.R;import com.example.jinritoutiao.Xiangq

Android——Xlistview上拉刷新下拉加载

配置网络权限+xutils包+gson包 代码如下: values下修改strings添加 直接粘 <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">XListView刷新</string> <string name="hello_world">Hello world!

Android XListView下拉刷新、上拉载入更多

source code: https://github.com/Maxwin-z/XListView-Android 提供了两个接口: a) IXListViewListener:  触发下拉刷新.上拉载入更多 b) OnXScrollListener: 这个和原生的OnScrollListener一样,但是在mScroller回滚时,也会触发这里的事件. bug fix 例子很好哦,不过有一个BUG,就是当最开始数据不能撑满屏幕的时候,也就是比如有1条,那么将ListView向上拉不会完美刷新

整合了刷新、加载更多、滑动删除功能的XListview

转载请说明出处:http://blog.csdn.net/bz419927089 如果想做带有刷新.加载更多功能的listview,我们可以使用XListview.(已经停止维护,github地址:https://github.com/Maxwin-z/XListView-Android) 如果想做带有滑动删除功能的listview,我们可以使用SwipeListview.(github地址:https://github.com/47deg/android-swipelistview) 如果想做

ListView的下拉刷新和上拉加载--XListView

分析XListView的源码,是因为其他开源控件代码都太多了(主要很多细微的地方都不懂,只能理解个大概),这个控件只是在原生ListView的基础上添加Header和Footer,代码很简单,可以随便折腾. Github地址:Github上搜索这个就行-----XListView-Android 看Header代码: /** * @file XListViewHeader.java * @create Apr 18, 2012 5:22:27 PM * @author Maxwin * @des

下拉刷新XListView的简单分析

依照这篇博文里的思路分析和理解的 先要理解Scroller,看过的博文: http://ipjmc.iteye.com/blog/1615828 http://blog.csdn.net/wangjinyu501/article/details/32339379 还要理解View的touch时间传递: http://www.codekk.com/open-source-project-analysis/detail/Android/Trinea/%E5%85%AC%E5%85%B1%E6%8A%

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的下拉刷新、上拉加载、用Pull解析XML

做之前需要导入XListview的文件,此是用第三方的xListview实现的,东西没写全.此是在Fragment中实现的 //--------------XListView的布局---------------- <me.XListView android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:id="@+id/lv&

支持下拉刷新和上划加载更多的自定义RecyclerView(仿XListView效果)

首先看效果 下拉刷新:        上划加载        在项目更新的过程中,遇到了一个将XListView换成recyclerView的需求,而且更换完之后大体效果不能变,但是对于下拉刷新这样的效果,谷歌给出的解决方案是把RecyclerView放在一个SwipeRefreshLayout中,但是这样其实是拉下一个小圆形控件实现的,和XListView的header效果不同.在网上找了很多的别人代码,都没有实现我想要的效果,于是自己动手写了一个. 具体实现的效果有以下几条 下拉刷新功能: