这似乎是Android中的一个相当常见的模式。我试图创建类似于Facebook显示其广告的东西:
你可以看到他们有一个外部的垂直RecyclerView,其中一个内部的水平RecyclerView是外部垂直RecyclerView适配器中的一项。我遵循了谷歌的“在ViewGroup中管理触摸事件”的指南 - http://developer.android.com/training/gestures/viewgroup.html,因为RecyclerView扩展了ViewGroup,那里的代码与我想要做的类似。我对其进行了一些自定义,以便它检测Y轴上的移动而不是X轴上的移动,并将其应用于外部垂直RecyclerView。
当我尝试拖动内部的水平RecyclerView(希望触摸事件会被外部的垂直RecyclerView截取),但外部的RecyclerView完全不会垂直滚动。同时它还会出现以下错误提示:“处理滚动时出错;未找到ID为-1的指针索引。是否有任何MotionEvents被跳过?”。有人知道如何正确解决这个问题吗?
/**
* Created by Simon on 10/11/2015.
*///This is the recyclerview that would allow all vertical scrolls
public class VerticallyScrollRecyclerView extends RecyclerView {
public VerticallyScrollRecyclerView(Context context) {
super(context);
}
public VerticallyScrollRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public VerticallyScrollRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
ViewConfiguration vc = ViewConfiguration.get(this.getContext());
private int mTouchSlop = vc.getScaledTouchSlop();
private boolean mIsScrolling;
private float startY;
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
final int action = MotionEventCompat.getActionMasked(ev);
// Always handle the case of the touch gesture being complete.
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
// Release the scroll.
mIsScrolling = false;
startY = ev.getY();
return false; // Do not intercept touch event, let the child handle it
}
switch (action) {
case MotionEvent.ACTION_MOVE: {
if (mIsScrolling) {
// We're currently scrolling, so yes, intercept the
// touch event!
return true;
}
// If the user has dragged her finger horizontally more than
// the touch slop, start the scroll
// left as an exercise for the reader
final float yDiff = calculateDistanceY(ev.getY());
Log.e("yDiff ", ""+yDiff);
// Touch slop should be calculated using ViewConfiguration
// constants.
if (yDiff > mTouchSlop) {
// Start scrolling!
Log.e("Scroll", "we are scrolling vertically");
mIsScrolling = true;
return true;
}
break;
}
}
return false;
}
private float calculateDistanceY(float endY) {
return startY - endY;
}
}
我的xml布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/main_recyclerview_holder">
<com.example.simon.customshapes.VerticallyScrollRecyclerView
android:id="@+id/main_recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
当我尝试拖动内部的水平RecyclerView(希望触摸事件会被外部的垂直RecyclerView截取),但外部的RecyclerView完全不会垂直滚动。同时它还会出现以下错误提示:“处理滚动时出错;未找到ID为-1的指针索引。是否有任何MotionEvents被跳过?”。有人知道如何正确解决这个问题吗?
VerticallyScrollRecyclerView
?不能只使用水平的LinearLayoutManager
吗? - rciovati