本文主要是介绍自定义布局实现listview上拉加载下拉刷新,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
listview布局有时加载数据偏多,需要上拉加载第二页等更多数据,下拉刷新数据等功能,也有开源的框架XRefreshView ,可以参考http://www.w2bc.com/Article/44291,当初开发项目时,便于自己控制,就自定义布局实现这功能。
1、自定义布局用来管理三个子控件:下拉头,包含内容的自定义listview,上拉头(代码有详细介绍)
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不可能同时不为0public 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接口的Viewprivate View pullableView;// 过滤多点触碰private int mEvents;// 这两个变量用来控制pull的方向,如果不加控制,当情况满足可上拉又可下拉时没法下拉private boolean canPullDown = true;private boolean canPullUp = true;/*** 执行自动回滚的handler*/Handler updateHandler = new Handler() {@Overridepublic 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();}if (pullUpY > 0) {// 已完成回弹pullUpY = 0;pullUpView.clearAnimation();// 隐藏下拉头时有可能还在刷新,只有当前状态不是正在刷新时才改变状态if (state != REFRESHING && state != LOADING)changeState(INIT);timer.cancel();}// 刷新布局,会自动调用onLayoutrequestLayout();}};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) {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代表失败* void**/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;}// 刷新结果停留1秒new Handler() {@Overridepublic void handleMessage(Message msg) {changeState(DONE);hide();}}.sendEmptyMessageDelayed(0, 1000);}/*** 加载完毕,显示加载结果(注意:加载完成后一定要调用这个方法)** @param refreshResult PullToRefreshLayout.SUCCEED代表成功,PullToRefreshLayout.FAIL代表失败* void**/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;}// 刷新结果停留1秒new Handler() {@Overridepublic void handleMessage(Message msg) {changeState(DONE);hide();}}.sendEmptyMessageDelayed(0, 1000);}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;}@Overridepublic 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 (((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 (((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;}} elsereleasePull();} elsemEvents = 0;lastY = ev.getY();// 根据下拉距离改变比例radio = (float) (2 + 2 * Math.tan(Math.PI / 2 / getMeasuredHeight()* (pullDownY + Math.abs(pullUpY))));requestLayout();if (pullDownY <= refreshDist && state == RELEASE_TO_REFRESH) {// 如果下拉距离没达到刷新的距离且当前状态是释放刷新,改变状态为下拉刷新changeState(INIT);}if (pullDownY >= refreshDist && state == INIT) {// 如果下拉距离达到刷新的距离且当前状态是初始状态刷新,改变状态为释放刷新changeState(RELEASE_TO_REFRESH);}// 下面是判断上拉加载的,同上,注意pullUpY是负值if (-pullUpY <= loadmoreDist && state == RELEASE_TO_LOAD) {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;}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);}@Overrideprotected void onLayout(boolean changed, int l, int t, int r, int b) {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;}@Overridepublic void run() {handler.obtainMessage().sendToTarget();}}}/*** 刷新加载回调接口*/public interface OnRefreshListener {/*** 刷新操作*/void onRefresh(PullToRefreshLayout pullToRefreshLayout);/*** 加载操作*/void onLoadMore(PullToRefreshLayout pullToRefreshLayout);}}
2、定义上拉下拉的事件的接口
public interface Pullable {/*** 判断是否可以下拉,如果不需要下拉功能可以直接return false** @创建日期 2015年10月19日** @return boolean true如果可以下拉否则返回false*/boolean canPullDown();/*** 判断是否可以上拉,如果不需要上拉功能可以直接return false** @创建日期 2015年10月19日** @return boolean true如果可以上拉否则返回false* */boolean canPullUp();
}
3、自定义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);}@Overridepublic boolean canPullDown() {if (getCount() == 0) { // 没有item的时候也可以下拉刷新return true;} else if (getFirstVisiblePosition() == 0&& getChildAt(0).getTop() >= 0) {// 滑到ListView的顶部return true;} else{return false;}}@Overridepublic 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;}
}
4、布局
<cn.com.supplier.view.PullToRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/project_refresh_view"android:layout_width="match_parent"android:layout_height="match_parent" ><!-- 下拉刷新布局 --><include layout="@layout/refresh_head" /><!-- 支持所有实现Pullable接口的View --><cn.com.supplier.view.PullableListView
android:id="@+id/list_enrollProject"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@color/bg"android:divider="@color/list_line"android:dividerHeight="1dp" /><!-- 上拉加载布局 --><include layout="@layout/load_more" /></cn.com.supplier.view.PullToRefreshLayout>
其中上拉和下拉的布局是分开引入的,自己可以根据样式自定义
5、调用
先获取自定义布局,实现自定义的刷新方法
((PullToRefreshLayout) findViewById(R.id.project_refresh_view)).setOnRefreshListener(new MyClickListener());class MyClickListener implements OnRefreshListener {/*** 下拉刷新操作*/@Overridepublic void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {new Handler() {@Overridepublic void handleMessage(Message msg) {pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);onDestroy();}}.sendEmptyMessageDelayed(0, 1000);}/*** 上拉加载更多操作*/@Overridepublic void onLoadMore(final PullToRefreshLayout pullToRefreshLayout) {new Handler() {@Overridepublic void handleMessage(Message msg) {//获取更多数据的方法loadProjectPost(signUrl);pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);}}.sendEmptyMessageDelayed(0, 1000);}}
这篇关于自定义布局实现listview上拉加载下拉刷新的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!