天天看点

android nestedscrollview 横向,Android RecyclerView在NestedScrollView中水平滚动很难做到

几个月前,我也遇到过同样的问题,唯一对我有效的解决方案是创建您自己的自定义RecyclerView和NestedScrollView:

MerohorizontalRecyclerView类

public class MeroHorizontalRecyclerView extends RecyclerView {

private GestureDetector mGestureDetector;

public MeroHorizontalRecyclerView(Context context) {

super(context);

init();

}

public MeroHorizontalRecyclerView(Context context, @Nullable AttributeSet attrs) {

super(context, attrs);

init();

}

public MeroHorizontalRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

init();

}

private void init() {

LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());

layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

setLayoutManager(layoutManager);

mGestureDetector = new GestureDetector(getContext(), new VerticalScrollDetector());

}

@Override

public boolean onInterceptTouchEvent(MotionEvent e) {

if (mGestureDetector.onTouchEvent(e)) {

return false;

}

return super.onInterceptTouchEvent(e);

}

public class VerticalScrollDetector extends

GestureDetector.SimpleOnGestureListener {

@Override

public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

return Math.abs(distanceY) > Math.abs(distanceX);

}

}

}

MeroneStedScrollView类

public class MeroNestedScrollView extends NestedScrollView {

public MeroNestedScrollView(Context context) {

super(context);

}

public MeroNestedScrollView(Context context, AttributeSet attrs) {

super(context, attrs);

}

public MeroNestedScrollView(Context context, AttributeSet attrs, int defStyleAttr) {

super(context, attrs, defStyleAttr);

}

private float xDistance, yDistance, lastX, lastY;

@Override

public boolean onInterceptTouchEvent(MotionEvent ev) {

final float x = ev.getX();

final float y = ev.getY();

switch (ev.getAction()) {

case MotionEvent.ACTION_DOWN:

xDistance = yDistance = 0f;

lastX = ev.getX();

lastY = ev.getY();

// This is very important line that fixes

computeScroll();

break;

case MotionEvent.ACTION_MOVE:

final float curX = ev.getX();

final float curY = ev.getY();

xDistance += Math.abs(curX - lastX);

yDistance += Math.abs(curY - lastY);

lastX = curX;

lastY = curY;

if (xDistance > yDistance) {

return false;

}

}

return super.onInterceptTouchEvent(ev);

}

}

现在以XML格式将它们导入为:

android:id="@+id/nestedScroll"

android:layout_width="match_parent"

android:layout_height="wrap_content">

android:id="@+id/recycler_view"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="@color/app_bg_color"/>

希望这有帮助!