天天看點

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"/>

希望這有幫助!