前面写过一篇关于下拉刷新控件的博客下拉刷新控件终结者:PullToRefreshLayout,后来看到好多人还有上拉加载更多的需求,于是就在前面下拉刷新控件的基础上进行了改进,加了上拉加载的功能。不仅如此,我已经把它改成了对所有View都通用!可以随心所欲使用这两个功能~~
我做了一个大集合的demo,实现了ListView、GridView、ExpandableListView、ScrollView、WebView、ImageView、TextView的下拉刷新和上拉加载。后面会提供demo的下载地址。
依照惯例,下面将会是一大波效果图:
demo首页也是可下拉的ListView,在底下可以加入table:
ListView:
GridView:
ExpandableListView:
ScrollView:
WebView:
ImageView:
TextView:
很不错吧?最后的ImageView和TextView是最简单的,直接在下面的接口方法里返回true。
增加上拉加载很简单,和管理下拉头一样,再多管理一个上拉头,也不费事;至于把它改成通用的就需要统一一下View的行为了,为此,我定义了这样一个接口:
[java]view plaincopypackagecom.jingchen.pulltorefresh.pullableview; publicinterfacePullable { /** *判断是否可以下拉,如果不需要下拉功能可以直接returnfalse * *@returntrue如果可以下拉否则返回false */ booleancanPullDown(); /** *判断是否可以上拉,如果不需要上拉功能可以直接returnfalse * *@returntrue如果可以上拉否则返回false */ booleancanPullUp(); } 从接口名就可以看出它是一个提供判断是否可拉的方法的接口。这个接口的两个方法,canPullDown()是判断何时可以下拉的方法,canPullUp()则是判断何时可以上拉,我在demo中的判断是滑到顶部的时候可以下拉,滑到底部的时候可以上拉。所有需要上拉和下拉的View都需要实现这个接口。后面会给出一些View的实现。先来看看改进后的自定义的布局PullToRefreshLayout,增加了一个上拉头,下拉头和上拉头之间的View是实现了Pullable接口的pullableView。相比前面的版本,这里有改动的需要注意的地方如下:
1、增加了上拉头,相应的也增加了控制变量。
2、拉动时消除content_view事件防止误触发不再使用反射,直接设置event.setAction(MotionEvent.ACTION_CANCEL)。
3、消除了拉动过程中的多点触碰导致的剧变。
4、不再设置content_view的onTouListener,让使用者可以更加自由的设置监听器。
这个PullToRefreshLayout只负责管理三个控件,如果一个View需要有上拉下拉功能则只需实现接口就行了。下面看PullToRefreshLayout的代码,注释写了好多:
[java]view plaincopypackagecom.jingchen.pulltorefresh; importjava.util.Timer; importjava.util.TimerTask; importandroid.content.Context; importandroid.graphics.Canvas; importandroid.graphics.LinearGradient; importandroid.graphics.Paint; importandroid.graphics.Paint.Style; importandroid.graphics.RectF; importandroid.graphics.Shader.TileMode; importandroid.os.Handler; importandroid.os.Message; importandroid.util.AttributeSet; importandroid.util.Log; importandroid.view.MotionEvent; importandroid.view.View; importandroid.view.ViewGroup; importandroid.view.animation.AnimationUtils; importandroid.view.animation.LinearInterpolator; importandroid.view.animation.RotateAnimation; importandroid.widget.RelativeLayout; importandroid.widget.TextView; importcom.jingchen.pulltorefresh.pullableview.Pullable; /** *自定义的布局,用来管理三个子控件,其中一个是下拉头,一个是包含内容的pullableView(可以是实现Pullable接口的的任何View), *还有一个上拉头 * *@author陈靖 */ publicclassPullToRefreshLayoutextendsRelativeLayout { publicstaticfinalStringTAG="PullToRefreshLayout"; //初始状态 publicstaticfinalintINIT=0; //释放刷新 publicstaticfinalintRELEASE_TO_REFRESH=1; //正在刷新 publicstaticfinalintREFRESHING=2; //释放加载 publicstaticfinalintRELEASE_TO_LOAD=3; //正在加载 publicstaticfinalintLOADING=4; //操作完毕 publicstaticfinalintDONE=5; //当前状态 privateintstate=INIT; //刷新回调接口 privateOnRefreshListenermListener; //刷新成功 publicstaticfinalintSUCCEED=0; //刷新失败 publicstaticfinalintFAIL=1; //按下Y坐标,上一个事件点Y坐标 privatefloatdownY,lastY; //下拉的距离。注意:pullDownY和pullUpY不可能同时不为0 publicfloatpullDownY=0; //上拉的距离 privatefloatpullUpY=0; //释放刷新的距离 privatefloatrefreshDist=200; //释放加载的距离 privatefloatloadmoreDist=200; privateMyTimertimer; //回滚速度 publicfloatMOVE_SPEED=8; //第一次执行布局 privatebooleanisLayout=false; //在刷新过程中滑动操作 privatebooleanisTouch=false; //手指滑动距离与下拉头的滑动距离比,中间会随正切函数变化 privatefloatradio=2; //下拉箭头的转180°动画 privateRotateAnimationrotateAnimation; //均匀旋转动画 privateRotateAnimationrefreshingAnimation; //下拉头 privateViewrefreshView; //下拉的箭头 privateViewpullView; //正在刷新的图标 privateViewrefreshingView; //刷新结果图标 privateViewrefreshStateImageView; //刷新结果:成功或失败 privateTextViewrefreshStateTextView; //上拉头 privateViewloadmoreView; //上拉的箭头 privateViewpullUpView; //正在加载的图标 privateViewloadingView; //加载结果图标 privateViewloadStateImageView; //加载结果:成功或失败 privateTextViewloadStateTextView; //实现了Pullable接口的View privateViewpullableView; //过滤多点触碰 privateintmEvents; //这两个变量用来控制pull的方向,如果不加控制,当情况满足可上拉又可下拉时没法下拉 privatebooleancanPullDown=true; privatebooleancanPullUp=true; /** *执行自动回滚的handler */ HandlerupdateHandler=newHandler() { @Override publicvoidhandleMessage(Messagemsg) { //回弹速度随下拉距离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(); }elseif(state==LOADING&&-pullUpY<=loadmoreDist) { pullUpY=-loadmoreDist; timer.cancel(); } } if(pullDownY>0) pullDownY-=MOVE_SPEED; elseif(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(); } //刷新布局,会自动调用onLayout requestLayout(); } }; publicvoidsetOnRefreshListener(OnRefreshListenerlistener) { mListener=listener; } publicPullToRefreshLayout(Contextcontext) { super(context); initView(context); } publicPullToRefreshLayout(Contextcontext,AttributeSetattrs) { super(context,attrs); initView(context); } publicPullToRefreshLayout(Contextcontext,AttributeSetattrs,intdefStyle) { super(context,attrs,defStyle); initView(context); } privatevoidinitView(Contextcontext) { timer=newMyTimer(updateHandler); rotateAnimation=(RotateAnimation)AnimationUtils.loadAnimation( context,R.anim.reverse_anim); refreshingAnimation=(RotateAnimation)AnimationUtils.loadAnimation( context,R.anim.rotating); //添加匀速转动动画 LinearInterpolatorlir=newLinearInterpolator(); rotateAnimation.setInterpolator(lir); refreshingAnimation.setInterpolator(lir); } privatevoidhide() { timer.schedule(5); } /** *完成刷新操作,显示刷新结果。注意:刷新完成后一定要调用这个方法 */ /** *@paramrefreshResult *PullToRefreshLayout.SUCCEED代表成功,PullToRefreshLayout.FAIL代表失败 */ publicvoidrefreshFinish(intrefreshResult) { refreshingView.clearAnimation(); refreshingView.setVisibility(View.GONE); switch(refreshResult) { caseSUCCEED: //刷新成功 refreshStateImageView.setVisibility(View.VISIBLE); refreshStateTextView.setText(R.string.refresh_succeed); refreshStateImageView .setBackgroundResource(R.drawable.refresh_succeed); break; caseFAIL: default: //刷新失败 refreshStateImageView.setVisibility(View.VISIBLE); refreshStateTextView.setText(R.string.refresh_fail); refreshStateImageView .setBackgroundResource(R.drawable.refresh_failed); break; } //刷新结果停留1秒 newHandler() { @Override publicvoidhandleMessage(Messagemsg) { changeState(DONE); hide(); } }.sendEmptyMessageDelayed(0,1000); } /** *加载完毕,显示加载结果。注意:加载完成后一定要调用这个方法 * *@paramrefreshResult *PullToRefreshLayout.SUCCEED代表成功,PullToRefreshLayout.FAIL代表失败 */ publicvoidloadmoreFinish(intrefreshResult) { loadingView.clearAnimation(); loadingView.setVisibility(View.GONE); switch(refreshResult) { caseSUCCEED: //加载成功 loadStateImageView.setVisibility(View.VISIBLE); loadStateTextView.setText(R.string.load_succeed); loadStateImageView.setBackgroundResource(R.drawable.load_succeed); break; caseFAIL: default: //加载失败 loadStateImageView.setVisibility(View.VISIBLE); loadStateTextView.setText(R.string.load_fail); loadStateImageView.setBackgroundResource(R.drawable.load_failed); break; } //刷新结果停留1秒 newHandler() { @Override publicvoidhandleMessage(Messagemsg) { changeState(DONE); hide(); } }.sendEmptyMessageDelayed(0,1000); } privatevoidchangeState(intto) { state=to; switch(state) { caseINIT: //下拉布局初始状态 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; caseRELEASE_TO_REFRESH: //释放刷新状态 refreshStateTextView.setText(R.string.release_to_refresh); pullView.startAnimation(rotateAnimation); break; caseREFRESHING: //正在刷新状态 pullView.clearAnimation(); refreshingView.setVisibility(View.VISIBLE); pullView.setVisibility(View.INVISIBLE); refreshingView.startAnimation(refreshingAnimation); refreshStateTextView.setText(R.string.refreshing); break; caseRELEASE_TO_LOAD: //释放加载状态 loadStateTextView.setText(R.string.release_to_load); pullUpView.startAnimation(rotateAnimation); break; caseLOADING: //正在加载状态 pullUpView.clearAnimation(); loadingView.setVisibility(View.VISIBLE); pullUpView.setVisibility(View.INVISIBLE); loadingView.startAnimation(refreshingAnimation); loadStateTextView.setText(R.string.loading); break; caseDONE: //刷新或加载完毕,啥都不做 break; } } /** *不限制上拉或下拉 */ privatevoidreleasePull() { canPullDown=true; canPullUp=true; } /* *(非Javadoc)由父控件决定是否分发事件,防止事件冲突 * *@seeandroid.view.ViewGroup#dispatchTouchEvent(android.view.MotionEvent) */ @Override publicbooleandispatchTouchEvent(MotionEventev) { switch(ev.getActionMasked()) { caseMotionEvent.ACTION_DOWN: downY=ev.getY(); lastY=downY; timer.cancel(); mEvents=0; releasePull(); break; caseMotionEvent.ACTION_POINTER_DOWN: caseMotionEvent.ACTION_POINTER_UP: //过滤多点触碰 mEvents=-1; break; caseMotionEvent.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; } }elseif(((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)))); requestLayout(); if(pullDownY<=refreshDist <spanstyle="white-space:pre"></span>&&(state==RELEASE_TO_REFRESH||state==DONE)){ <spanstyle="white-space:pre"></span>//如果下拉距离没达到刷新的距离且当前状态是释放刷新,改变状态为下拉刷新 <spanstyle="white-space:pre"></span>changeState(INIT); <spanstyle="white-space:pre"></span>} <spanstyle="white-space:pre"></span>if(pullDownY>=refreshDist&&(state==INIT||state==DONE)){ <spanstyle="white-space:pre"></span>//如果下拉距离达到刷新的距离且当前状态是初始状态刷新,改变状态为释放刷新 <spanstyle="white-space:pre"></span>changeState(RELEASE_TO_REFRESH); <spanstyle="white-space:pre"></span>} <spanstyle="white-space:pre"></span>//下面是判断上拉加载的,同上,注意pullUpY是负值 <spanstyle="white-space:pre"></span>if(-pullUpY<=loadmoreDist <spanstyle="white-space:pre"></span>&&(state==RELEASE_TO_LOAD||state==DONE)){ <spanstyle="white-space:pre"></span>changeState(INIT); <spanstyle="white-space:pre"></span>} <spanstyle="white-space:pre"></span>if(-pullUpY>=loadmoreDist&&(state==INIT||state==DONE)){ <spanstyle="white-space:pre"></span>changeState(RELEASE_TO_LOAD); <spanstyle="white-space:pre"></span>} //因为刷新和加载操作不能同时进行,所以pullDownY和pullUpY不会同时不为0,因此这里用(pullDownY+ //Math.abs(pullUpY))就可以不对当前状态作区分了 if((pullDownY+Math.abs(pullUpY))>8) { //防止下拉过程中误触发长按事件和点击事件 ev.setAction(MotionEvent.ACTION_CANCEL); } break; caseMotionEvent.ACTION_UP: if(pullDownY>refreshDist||-pullUpY>loadmoreDist) //正在刷新时往下拉(正在加载时往上拉),释放后下拉头(上拉头)不隐藏 isTouch=false; if(state==RELEASE_TO_REFRESH) { changeState(REFRESHING); //刷新操作 if(mListener!=null) mListener.onRefresh(this); }elseif(state==RELEASE_TO_LOAD) { changeState(LOADING); //加载操作 if(mListener!=null) mListener.onLoadMore(this); } hide(); default: break; } //事件分发交给父类 super.dispatchTouchEvent(ev); returntrue; } privatevoidinitView() { //初始化下拉布局 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 protectedvoidonLayout(booleanchanged,intl,intt,intr,intb) { 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()); } classMyTimer { privateHandlerhandler; privateTimertimer; privateMyTaskmTask; publicMyTimer(Handlerhandler) { this.handler=handler; timer=newTimer(); } publicvoidschedule(longperiod) { if(mTask!=null) { mTask.cancel(); mTask=null; } mTask=newMyTask(handler); timer.schedule(mTask,0,period); } publicvoidcancel() { if(mTask!=null) { mTask.cancel(); mTask=null; } } classMyTaskextendsTimerTask { privateHandlerhandler; publicMyTask(Handlerhandler) { this.handler=handler; } @Override publicvoidrun() { handler.obtainMessage().sendToTarget(); } } } /** *刷新加载回调接口 * *@authorchenjing * */ publicinterfaceOnRefreshListener { /** *刷新操作 */ voidonRefresh(PullToRefreshLayoutpullToRefreshLayout); /** *加载操作 */ voidonLoadMore(PullToRefreshLayoutpullToRefreshLayout); } } 上面就是整个布局的代码,并不是很难。
下面看各个View对Pullable接口的实现,ListView和GridView还有ExpandableListView的判断方法是一样的:
PullableListView:
[java]view plaincopypackagecom.jingchen.pulltorefresh.pullableview; importandroid.content.Context; importandroid.util.AttributeSet; importandroid.util.Log; importandroid.widget.ListView; publicclassPullableListViewextendsListViewimplementsPullable { publicPullableListView(Contextcontext) { super(context); } publicPullableListView(Contextcontext,AttributeSetattrs) { super(context,attrs); } publicPullableListView(Contextcontext,AttributeSetattrs,intdefStyle) { super(context,attrs,defStyle); } @Override publicbooleancanPullDown() { if(getCount()==0) { //没有item的时候也可以下拉刷新 returntrue; }elseif(getFirstVisiblePosition()==0 &&getChildAt(0).getTop()>=0) { //滑到ListView的顶部了 returntrue; }else returnfalse; } @Override publicbooleancanPullUp() { if(getCount()==0) { //没有item的时候也可以上拉加载 returntrue; }elseif(getLastVisiblePosition()==(getCount()-1)) { //滑到底部了 if(getChildAt(getLastVisiblePosition()-getFirstVisiblePosition())!=null &&getChildAt( getLastVisiblePosition() -getFirstVisiblePosition()).getBottom()<=getMeasuredHeight()) returntrue; } returnfalse; } }
PullableExpandableListView:
[java]view plaincopypackagecom.jingchen.pulltorefresh.pullableview; importandroid.content.Context; importandroid.util.AttributeSet; importandroid.widget.ExpandableListView; publicclassPullableExpandableListViewextendsExpandableListViewimplements Pullable { publicPullableExpandableListView(Contextcontext) { super(context); } publicPullableExpandableListView(Contextcontext,AttributeSetattrs) { super(context,attrs); } publicPullableExpandableListView(Contextcontext,AttributeSetattrs, intdefStyle) { super(context,attrs,defStyle); } @Override publicbooleancanPullDown() { if(getCount()==0) { //没有item的时候也可以下拉刷新 returntrue; }elseif(getFirstVisiblePosition()==0 &&getChildAt(0).getTop()>=0) { //滑到顶部了 returntrue; }else returnfalse; } @Override publicbooleancanPullUp() { if(getCount()==0) { //没有item的时候也可以上拉加载 returntrue; }elseif(getLastVisiblePosition()==(getCount()-1)) { //滑到底部了 if(getChildAt(getLastVisiblePosition()-getFirstVisiblePosition())!=null &&getChildAt( getLastVisiblePosition() -getFirstVisiblePosition()).getBottom()<=getMeasuredHeight()) returntrue; } returnfalse; } }
PullableGridView:
[java]view plaincopypackagecom.jingchen.pulltorefresh.pullableview; importandroid.content.Context; importandroid.util.AttributeSet; importandroid.widget.GridView; publicclassPullableGridViewextendsGridViewimplementsPullable { publicPullableGridView(Contextcontext) { super(context); } publicPullableGridView(Contextcontext,AttributeSetattrs) { super(context,attrs); } publicPullableGridView(Contextcontext,AttributeSetattrs,intdefStyle) { super(context,attrs,defStyle); } @Override publicbooleancanPullDown() { if(getCount()==0) { //没有item的时候也可以下拉刷新 returntrue; }elseif(getFirstVisiblePosition()==0 &&getChildAt(0).getTop()>=0) { //滑到顶部了 returntrue; }else returnfalse; } @Override publicbooleancanPullUp() { if(getCount()==0) { //没有item的时候也可以上拉加载 returntrue; }elseif(getLastVisiblePosition()==(getCount()-1)) { //滑到底部了 if(getChildAt(getLastVisiblePosition()-getFirstVisiblePosition())!=null &&getChildAt( getLastVisiblePosition() -getFirstVisiblePosition()).getBottom()<=getMeasuredHeight()) returntrue; } returnfalse; } }
PullableScrollView:[java]view plaincopypackagecom.jingchen.pulltorefresh.pullableview; importandroid.content.Context; importandroid.util.AttributeSet; importandroid.widget.ScrollView; publicclassPullableScrollViewextendsScrollViewimplementsPullable { publicPullableScrollView(Contextcontext) { super(context); } publicPullableScrollView(Contextcontext,AttributeSetattrs) { super(context,attrs); } publicPullableScrollView(Contextcontext,AttributeSetattrs,intdefStyle) { super(context,attrs,defStyle); } @Override publicbooleancanPullDown() { if(getScrollY()==0) returntrue; else returnfalse; } @Override publicbooleancanPullUp() { if(getScrollY()>=(getChildAt(0).getHeight()-getMeasuredHeight())) returntrue; else returnfalse; } }
PullableWebView:[java]view plaincopypackagecom.jingchen.pulltorefresh.pullableview; importandroid.content.Context; importandroid.util.AttributeSet; importandroid.webkit.WebView; publicclassPullableWebViewextendsWebViewimplementsPullable { publicPullableWebView(Contextcontext) { super(context); } publicPullableWebView(Contextcontext,AttributeSetattrs) { super(context,attrs); } publicPullableWebView(Contextcontext,AttributeSetattrs,intdefStyle) { super(context,attrs,defStyle); } @Override publicbooleancanPullDown() { if(getScrollY()==0) returntrue; else returnfalse; } @Override publicbooleancanPullUp() { if(getScrollY()>=getContentHeight()*getScale() -getMeasuredHeight()) returntrue; else returnfalse; } }
ImageView和TextView就不贴了,我直接在方法里返回了true。
OK了,整个demo的代码有点多,就不贴了。
demo下载