SwipeRefreshLayout 与ListView滑动冲突问题
在SwipeRefreshLayout控件中,只能够放ListView或者LinearLayout单一控件,当SwipeRefreshLayout中放两个或多个并列布局时,就会出现滑动冲突问题:
- 如下布局,就会出现冲突问题,当向下滑动ListView时,SwipeRefreshLayout会优先获取事件。导致ListView不能够正常下拉。
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swip_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white"
android:gravity="center_vertical"
android:orientation="vertical"
android:paddingBottom="9dp"
android:paddingTop="9dp" >
<View
android:id="@+id/view1"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="10dp"
android:background="@color/home_fenge_line" />
</LinearLayout>
</LinearLayout>
<ImageView
android:id="@+id/iv_sawtooth"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/buy_list_details_sawtooth"
android:contentDescription="@string/image_content" />
<ListView
android:id="@+id/lv_list"
style="@style/pulltorefreshDividerListview"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
</android.support.v4.widget.SwipeRefreshLayout>
怎么解决呢???
分析可以得到,有与SwipeRefreshLayout已经封装了方法,我们可以利用已有的方法来解决滑动冲突:
思路如下:判断ListView是否滑动到第一条数据,如果是,则SwipeRefreshLayout才获取事件(能够下拉刷新)。反之,让ListView 获取事件。那么我们可以实现让ListView OnScrollListener接口,在OnScroll和onScrollStateChanged两个方法中做出相应的判断:
ok,思路已经有了,代码如下:
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
this.lastItem = firstVisibleItem + visibleItemCount;
this.totalItem = totalItemCount;
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (this.totalItem == lastItem && scrollState == SCROLL_STATE_IDLE) {
Log.v("isLoading", "yes");
if (!isLoading) {
isLoading = true;
footer.setVisibility(View.VISIBLE);
onLoadMore.loadMore();//上拉加载
}
}
//判断ListView是否滑动到第一个Item的顶部
if (isValid!=null&&this.getChildCount() > 0 && this.getFirstVisiblePosition() == 0
&& this.getChildAt(0).getTop() >= this.getPaddingTop()) {
//解决滑动冲突,当滑动到第一个item,下拉刷新才起作用
isValid.setSwipeEnabledTrue();
} else {
isValid.setSwipeEnabledFalse();
}
}
ok,我们只需写个接口,给Swipe回调就行:
public interface OnSwipeIsValid{
public void setSwipeEnabledTrue();
public void setSwipeEnabledFalse();
}
实现接口:
lvList.setSwipeIsVaildListenr(this);//ListView设置实现接口
@Override
public void setSwipeEnabledTrue() {
swipe.setEnabled(true);//让swipe起作用,能够刷新
}
@Override
public void setSwipeEnabledFalse() {
swipe.setEnabled(false);//让swipe不能够刷新
}
ok,分析完成。