平时我们滑动的时候都知道ScrollView都是带有惯性滑动效果的。但是在5.0以上系统使用NestedScrollView嵌套RecyleView时,惯性滑动会失效,滑起来会感觉很不顺畅。那怎么解决呢?
1.禁止RecyclerView 的滑动
方法很简单,一般我们这么嵌套都是为了让外部NestedScrollView滑动而recyclerView不滑动的,所以我们只要让recyclerView不可滑动就可以了。recyclerView是否可左右、上下滑动,是由LayoutManager的canScrollHorizontally和canScrollVertically方法控制的,我们让相应的方法返回false就可以了。代码如下:
LinearLayoutManager manager = new LinearLayoutManager(getContext()){
@Override
public boolean canScrollVertically() {
return false;
}
};
commentRecyclerView.setLayoutManager(manager);
这样就可以滑到recyclerView的时候依旧丝般顺滑了!
2.通过事件分发的方法解决
重写ScrollView自定义类
class MyScrollView extends ScrollView {
private int downX;
private int downY;
private int mTouchSlop;
public MyScrollView(Context context) {
super(context);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
public MyScrollview(Context context, AttributeSet attrs) {
super(context, attrs);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
public MyScrollview(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
int action = e.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downX = (int) e.getRawX();
downY = (int) e.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int moveY = (int) e.getRawY();
if (Math.abs(moveY - downY) > mTouchSlop) {
return true;
}
}
return super.onInterceptTouchEvent(e);
}
}