最近项目中使用到了CoordinatorLayout这种布局方式,搭配RecycleView,实现起来比较简单,而且不用自己处理滑动事件,但是改为了ListView后发生了滑动冲突.
所以想到了以下解决方案:
1.使用事件分发,当ListView在Y轴滑动时,将事件交给CoordinatorLayout处理,无效!!!
2.取消ListView在Y轴的滑动,计算手指移动的距离,交给CoordinatorLayout来scroll,无效!!!
以上都不行,google了下,发现由于由于CoordinatorLayout实现NestedScrollingParent接口,RecycleView实现了NestedScrollingChild接口,所以就可以在NestedScrollingChildHelper的帮助下实现滑动联动,知道了原因这就简单了,让我们的LIstView实现NestedScrollingChild接口,查看下NestedScrollingChild接口的源码
实现这个接口必须创建NestedScrollingChildHelper,并且将View的方法交给NestedScrollingChildHelper的同名方法来处理,所以我们就在自定义ListView中加入
- public class MyListView extends ListView implements NestedScrollingChild{
- private final NestedScrollingChildHelper mScrollingChildHelper;
- public MyListView(Context context, AttributeSet attrs) {
- super(context, attrs);
- mScrollingChildHelper = new NestedScrollingChildHelper(this);
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
- setNestedScrollingEnabled(true);
- }
- }
- @Override
- public void setNestedScrollingEnabled(boolean enabled) {
- mScrollingChildHelper.setNestedScrollingEnabled(enabled);
- }
- @Override
- public boolean isNestedScrollingEnabled() {
- return mScrollingChildHelper.isNestedScrollingEnabled();
- }
- @Override
- public boolean startNestedScroll(int axes) {
- return mScrollingChildHelper.startNestedScroll(axes);
- }
- @Override
- public void stopNestedScroll() {
- mScrollingChildHelper.stopNestedScroll();
- }
- @Override
- public boolean hasNestedScrollingParent() {
- return mScrollingChildHelper.hasNestedScrollingParent();
- }
- @Override
- public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed,
- int dyUnconsumed, int[] offsetInWindow) {
- return mScrollingChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed,
- dxUnconsumed, dyUnconsumed, offsetInWindow);
- }
- @Override
- public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
- return mScrollingChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow);
- }
- @Override
- public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
- return mScrollingChildHelper.dispatchNestedFling(velocityX, velocityY, consumed);
- }
- @Override
- public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
- return mScrollingChildHelper.dispatchNestedPreFling(velocityX, velocityY);
- }
- 最后在xml中
- <android.support.v4.widget.NestedScrollView
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:fillViewport="true"
- app:layout_behavior="@string/appbar_scrolling_view_behavior">
- <com.dipaitv.widget.MyListView
- android:id="@+id/listview"
- android:layout_width="match_parent"
- android:layout_height="wrap_content">
- </com.dipaitv.widget.MyListView>
- </android.support.v4.widget.NestedScrollView>