在常规的需求中需要给ListView,ExpandableListView等具有滚动效果的控件添加上拉刷新控件(如:PtrClassicFrameLayout(可定制头部样式),SwipeRefreshLayout),那么问题来了,当列表滑动到底部,向上滑动的时候,还没有到达列表的顶部,Scroll事件被拦截,列表无法滚动同时上拉刷新被触发,这明显影响用户的体验效果。
具体的解决思路:重写一个滚动监听Listener
public class PtrListViewOnScrollListener implements AbsListView.OnScrollListener{
//如果集成了异步加载网络图片框架,需要加入ImageLoader,具体使用好处是:ImageLoader#pause() pause ImageLoader's tasks} while list view is scrolling (touch scrolling and/or * fling). It prevents redundant loadings. 不需要的话直接在构造方法中去掉即可
private ImageLoader imageLoader;
public PtrHTFrameLayout mPtrLayout;
private final booleanpause OnScroll;
private final booleanpause OnFling;
private final AbsListView.OnScrollListener externalListener;
public PtrListViewOnScrollListener(PtrHTFrameLayout mPtrLayout,ImageLoader imageLoader, boolean pauseOnScroll, boolean pauseOnFling) {
this(mPtrLayout,imageLoader,pauseOnScroll,pauseOnFling, null);
}
public PtrListViewOnScrollListener(PtrHTFrameLayout mPtrLayout,ImageLoader imageLoader, boolean pauseOnScroll, boolean pauseOnFling,AbsListView.OnScrollListener customListener) {
this.mPtrLayout= mPtrLayout;
this.imageLoader= imageLoader;
this.pauseOnScroll= pauseOnScroll;
this.pauseOnFling= pauseOnFling;
externalListener= customListener;
}
@Override
public void onScrollStateChanged(AbsListView view, intscrollState) {
switch(scrollState) {
case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
imageLoader.resume();
break;
case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
if(pauseOnScroll) {
imageLoader.pause();
}
break;
case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
if(pauseOnFling) {
imageLoader.pause();
}
break;
}
if(externalListener!=null) {
externalListener.onScrollStateChanged(view,scrollState);
}
}
@Override
public void onScroll(AbsListView view, intfirstVisibleItem, intvisibleItemCount, inttotalItemCount) {
//解决listView滑动与下拉刷新冲突问题
// 当firstVisibleItem是第0位。如果firstView==null说明列表为空,
// 需要刷新;或者top==0说明已经到达列表顶部, 也需要刷新
View firstView = view.getChildAt(firstVisibleItem);
if(firstVisibleItem ==0&& (firstView ==null|| firstView.getTop() ==0)) {
mPtrLayout.setEnabled(true);
}else{
mPtrLayout.setEnabled(false);
}
if(externalListener!=null) {
externalListener.onScroll(view,firstVisibleItem,visibleItemCount,totalItemCount);
}
}
}
代码中的使用:
private PtrListViewOnScrollListener ptrListViewOnScrollListener;
ptrListViewOnScrollListener=new PtrListViewOnScrollListener(mPtrLayout,MyApplication.imageLoader, true, false);
listView.setOnScrollListener(ptrListViewOnScrollListener);
//结束