当SwipeRefreshLayout只有ListView一个子view的时候是没有任何问题的,但如果不是一个子view就会出现问题了,向上滑动ListView一切正常,向下滑动的时候就会出现还没有滑倒ListView顶部就触发下拉刷新的动作了。
从SwipeRefreshLayout源码可以看到在onInterceptTouchEvent里面有这样的一段代码
if (!isEnabled() || mReturningToStart || canChildScrollUp() || mRefreshing) {
// Fail fast if we’re not in a state where a swipe is possible
return false;
}
其中有个canChildScrollUp方法
public boolean canChildScrollUp() {
if (android.os.Build.VERSION.SDK_INT < 14) {
if (mTarget instanceof AbsListView) {
final AbsListView absListView = (AbsListView) mTarget;
return absListView.getChildCount() > 0
&& (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
.getTop() < absListView.getPaddingTop());
} else {
return ViewCompat.canScrollVertically(mTarget, -1) || mTarget.getScrollY() > 0;
}
} else {
return ViewCompat.canScrollVertically(mTarget, -1);
}
}
决定子view 能否滑动就再canChildScrollUp方法中,所以我们只需写一个类继承SwipeRefreshLayout,然后重写该方法即可
public class SimpleSwipeRefreshLayout extends SwipeRefreshLayout {
private View view;
public SimpleSwipeRefreshLayout(Context context) {
super(context);
}
public SimpleSwipeRefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setViewGroup(View view) {
this.view = view;
}
@Override
public boolean canChildScrollUp() {
if (view != null && view instanceof AbsListView) {
final AbsListView absListView = (AbsListView) view;
return absListView.getChildCount() > 0
&& (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
.getTop() < absListView.getPaddingTop());
}
return super.canChildScrollUp();
}
}
但有时你发现并不如意,再对ListView设置如下OnScrollListener事件
listView.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
boolean enable = false;
if(listView != null && listView.getChildCount() > 0){
// 检查listView第一个item是否可见
boolean firstItemVisible = listView.getFirstVisiblePosition() == 0;
// 检查第一个item的顶部是否可见
boolean topOfFirstItemVisible = listView.getChildAt(0).getTop() == 0;
// 启用或者禁用SwipeRefreshLayout刷新标识
enable = firstItemVisible && topOfFirstItemVisible;
}else if (listView != null && listView.getChildCount() == 0) {
// 没有数据的时候允许刷新
enable = true;
}
// 把标识传给swipeRefreshLayout
swipeRefreshLayout.setEnabled(enable);
}});
你再看看,问题是否解决了!