226

我有一个 ScrollView 围绕我的整个布局,以便整个屏幕是可滚动的。我在这个 ScrollView 中的第一个元素是一个 Horizo​​ntalScrollView 块,它具有可以水平滚动的功能。我在水平滚动视图中添加了一个 ontouchlistener 来处理触摸事件并强制视图“捕捉”到 ACTION_UP 事件上最近的图像。

所以我想要的效果就像普通的 android 主屏幕,你可以从一个屏幕滚动到另一个屏幕,当你抬起手指时它会捕捉到一个屏幕。

这一切都很好,除了一个问题:我需要从左到右几乎完美地水平滑动才能注册 ACTION_UP。如果我至少垂直滑动(我认为很多人在左右滑动时倾向于在手机上这样做),我将收到 ACTION_CANCEL 而不是 ACTION_UP。我的理论是这是因为水平滚动视图在滚动视图中,滚动视图劫持垂直触摸以允许垂直滚动。

如何在我的水平滚动视图中禁用滚动视图的触摸事件,但仍允许在滚动视图的其他地方正常垂直滚动?

这是我的代码示例:

   public class HomeFeatureLayout extends HorizontalScrollView {
    private ArrayList<ListItem> items = null;
    private GestureDetector gestureDetector;
    View.OnTouchListener gestureListener;
    private static final int SWIPE_MIN_DISTANCE = 5;
    private static final int SWIPE_THRESHOLD_VELOCITY = 300;
    private int activeFeature = 0;

    public HomeFeatureLayout(Context context, ArrayList<ListItem> items){
        super(context);
        setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        setFadingEdgeLength(0);
        this.setHorizontalScrollBarEnabled(false);
        this.setVerticalScrollBarEnabled(false);
        LinearLayout internalWrapper = new LinearLayout(context);
        internalWrapper.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        internalWrapper.setOrientation(LinearLayout.HORIZONTAL);
        addView(internalWrapper);
        this.items = items;
        for(int i = 0; i< items.size();i++){
            LinearLayout featureLayout = (LinearLayout) View.inflate(this.getContext(),R.layout.homefeature,null);
            TextView header = (TextView) featureLayout.findViewById(R.id.featureheader);
            ImageView image = (ImageView) featureLayout.findViewById(R.id.featureimage);
            TextView title = (TextView) featureLayout.findViewById(R.id.featuretitle);
            title.setTag(items.get(i).GetLinkURL());
            TextView date = (TextView) featureLayout.findViewById(R.id.featuredate);
            header.setText("FEATURED");
            Image cachedImage = new Image(this.getContext(), items.get(i).GetImageURL());
            image.setImageDrawable(cachedImage.getImage());
            title.setText(items.get(i).GetTitle());
            date.setText(items.get(i).GetDate());
            internalWrapper.addView(featureLayout);
        }
        gestureDetector = new GestureDetector(new MyGestureDetector());
        setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                else if(event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL ){
                    int scrollX = getScrollX();
                    int featureWidth = getMeasuredWidth();
                    activeFeature = ((scrollX + (featureWidth/2))/featureWidth);
                    int scrollTo = activeFeature*featureWidth;
                    smoothScrollTo(scrollTo, 0);
                    return true;
                }
                else{
                    return false;
                }
            }
        });
    }

    class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                //right to left 
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    activeFeature = (activeFeature < (items.size() - 1))? activeFeature + 1:items.size() -1;
                    smoothScrollTo(activeFeature*getMeasuredWidth(), 0);
                    return true;
                }  
                //left to right
                else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    activeFeature = (activeFeature > 0)? activeFeature - 1:0;
                    smoothScrollTo(activeFeature*getMeasuredWidth(), 0);
                    return true;
                }
            } catch (Exception e) {
                // nothing
            }
            return false;
        }
    }
}
4

9 回答 9

283

更新:我想通了。在我的 ScrollView 上,我需要重写 onInterceptTouchEvent 方法以仅在 Y 运动大于 X 运动时拦截触摸事件。似乎 ScrollView 的默认行为是在有任何 Y 运动时拦截触摸事件。因此,通过修复,如果用户故意在 Y 方向滚动并且在这种情况下将 ACTION_CANCEL 传递给孩子,则 ScrollView 只会拦截事件。

这是包含 Horizo​​ntalScrollView 的 Scroll View 类的代码:

public class CustomScrollView extends ScrollView {
    private GestureDetector mGestureDetector;

    public CustomScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mGestureDetector = new GestureDetector(context, new YScrollDetector());
        setFadingEdgeLength(0);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return super.onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev);
    }

    // Return false if we're scrolling in the x direction  
    class YScrollDetector extends SimpleOnGestureListener {
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {             
            return Math.abs(distanceY) > Math.abs(distanceX);
        }
    }
}
于 2010-04-16T19:51:34.933 回答
178

感谢 Joel 为我提供了有关如何解决此问题的线索。

我简化了代码(不需要GestureDetector)以达到相同的效果:

public class VerticalScrollView extends ScrollView {
    private float xDistance, yDistance, lastX, lastY;

    public VerticalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                xDistance = yDistance = 0f;
                lastX = ev.getX();
                lastY = ev.getY();
                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);
    }
}
于 2011-10-09T13:12:27.130 回答
60

我想我找到了一个更简单的解决方案,只有它使用 ViewPager 的子类而不是(其父级)ScrollView。

更新 2013-07-16:我也添加了一个覆盖onTouchEvent。尽管 YMMV,它可能有助于解决评论中提到的问题。

public class UninterceptableViewPager extends ViewPager {

    public UninterceptableViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean ret = super.onInterceptTouchEvent(ev);
        if (ret)
            getParent().requestDisallowInterceptTouchEvent(true);
        return ret;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        boolean ret = super.onTouchEvent(ev);
        if (ret)
            getParent().requestDisallowInterceptTouchEvent(true);
        return ret;
    }
}

这类似于android.widget.Gallery 的 onScroll() 中使用的技术Google I/O 2013 演示文稿为 Android 编写自定义视图进一步解释了这一点。

2013-12-10 更新: Kirill Grouchnikov 关于(当时的)Android Market 应用程序的帖子中也描述了类似的方法。

于 2012-04-24T09:15:43.453 回答
14

我发现有时一个 ScrollView 重新获得焦点,而另一个失去焦点。您可以通过仅授予一个 scrollView 焦点来防止这种情况:

    scrollView1= (ScrollView) findViewById(R.id.scrollscroll);
    scrollView1.setAdapter(adapter);
    scrollView1.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            scrollView1.getParent().requestDisallowInterceptTouchEvent(true);
            return false;
        }
    });
于 2012-11-27T20:10:19.310 回答
8

这对我来说效果不佳。我改变了它,现在它工作顺利。如果有人感兴趣。

public class ScrollViewForNesting extends ScrollView {
    private final int DIRECTION_VERTICAL = 0;
    private final int DIRECTION_HORIZONTAL = 1;
    private final int DIRECTION_NO_VALUE = -1;

    private final int mTouchSlop;
    private int mGestureDirection;

    private float mDistanceX;
    private float mDistanceY;
    private float mLastX;
    private float mLastY;

    public ScrollViewForNesting(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);

        final ViewConfiguration configuration = ViewConfiguration.get(context);
        mTouchSlop = configuration.getScaledTouchSlop();
    }

    public ScrollViewForNesting(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ScrollViewForNesting(Context context) {
        this(context,null);
    }    


    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {      
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mDistanceY = mDistanceX = 0f;
                mLastX = ev.getX();
                mLastY = ev.getY();
                mGestureDirection = DIRECTION_NO_VALUE;
                break;
            case MotionEvent.ACTION_MOVE:
                final float curX = ev.getX();
                final float curY = ev.getY();
                mDistanceX += Math.abs(curX - mLastX);
                mDistanceY += Math.abs(curY - mLastY);
                mLastX = curX;
                mLastY = curY;
                break;
        }

        return super.onInterceptTouchEvent(ev) && shouldIntercept();
    }


    private boolean shouldIntercept(){
        if((mDistanceY > mTouchSlop || mDistanceX > mTouchSlop) && mGestureDirection == DIRECTION_NO_VALUE){
            if(Math.abs(mDistanceY) > Math.abs(mDistanceX)){
                mGestureDirection = DIRECTION_VERTICAL;
            }
            else{
                mGestureDirection = DIRECTION_HORIZONTAL;
            }
        }

        if(mGestureDirection == DIRECTION_VERTICAL){
            return true;
        }
        else{
            return false;
        }
    }
}
于 2014-03-05T13:58:55.623 回答
6

感谢Neevek,他的回答对我有用,但是当用户开始在水平方向滚动水平视图(ViewPager)然后不垂直抬起手指滚动它开始滚动底层容器视图(ScrollView)时,它不会锁定垂直滚动. 我通过对 Neevak 的代码稍作改动来修复它:

private float xDistance, yDistance, lastX, lastY;

int lastEvent=-1;

boolean isLastEventIntercepted=false;
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    switch (ev.getAction()) {
        case MotionEvent.ACTION_DOWN:
            xDistance = yDistance = 0f;
            lastX = ev.getX();
            lastY = ev.getY();


            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(isLastEventIntercepted && lastEvent== MotionEvent.ACTION_MOVE){
                return false;
            }

            if(xDistance > yDistance )
                {

                isLastEventIntercepted=true;
                lastEvent = MotionEvent.ACTION_MOVE;
                return false;
                }


    }

    lastEvent=ev.getAction();

    isLastEventIntercepted=false;
    return super.onInterceptTouchEvent(ev);

}
于 2013-11-07T18:28:09.183 回答
5

这最终成为支持 v4 库NestedScrollView的一部分。因此,我猜大多数情况下不再需要本地黑客。

于 2015-10-18T08:27:07.600 回答
1

Neevek 的解决方案在运行 3.2 及更高版本的设备上比 Joel 的解决方案效果更好。如果在 scollview 中使用手势检测器,Android 中有一个错误会导致 java.lang.IllegalArgumentException:pointerIndex out of range。要复制该问题,请按照 Joel 的建议实施自定义 scollview,并在其中放置一个视图寻呼机。如果你拖动(不要抬起你的身影)到一个方向(左/右),然后到相反的方向,你会看到崩溃。同样在 Joel 的解决方案中,如果您通过沿对角线移动手指来拖动视图寻呼机,一旦您的手指离开视图寻呼机的内容视图区域,寻呼机将弹回其先前的位置。所有这些问题更多地与 Android 的内部设计或缺乏它有关,而不是 Joel 的实现,它本身就是一段聪明而简洁的代码。

http://code.google.com/p/android/issues/detail?id=18990

于 2013-02-01T20:53:32.540 回答
0

日期:2021 年 - 5 月 12 日

看起来很乱..但相信我,如果您想在垂直滚动视图中水平滚动任何视图黄油光滑,那么值得花时间!

通过制作自定义视图并扩展您想要水平滚动的视图,也可以在 jetpack compose 中工作;在垂直滚动视图中并在可组合的 AndroidView 中使用该自定义视图(现在,“Jetpack Compose 在 1.0.0-beta06 中”

如果您想在水平滚动时不让垂直滚动条拦截您的触摸并且只允许垂直滚动条在您通过水平滚动视图垂直滚动时拦截您的触摸,那么这是最佳的解决方案:

private class HorizontallyScrollingView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : ViewThatYouWannaScrollHorizontally(context, attrs){
    override fun onTouchEvent(event: MotionEvent?): Boolean {

        // When the user's finger touches the webview and starts moving
        if(event?.action == MotionEvent.ACTION_MOVE){
            // get the velocity tracker object
            val mVelocityTracker = VelocityTracker.obtain();

            // connect the velocity tracker object with the event that we are emitting while we are touching the webview
            mVelocityTracker.addMovement(event)

            // compute the velocity in terms of pixels per 1000 millisecond(i.e 1 second)
            mVelocityTracker.computeCurrentVelocity(1000);

            // compute the Absolute Velocity in X axis
            val xVelocityABS = abs(mVelocityTracker.getXVelocity(event?.getPointerId((event?.actionIndex))));

            // compute the Absolute Velocity in Y axis
            val yVelocityABS = abs(mVelocityTracker.getYVelocity(event?.getPointerId((event?.actionIndex))));

            // If the velocity of x axis is greater than y axis then we'll consider that it's a horizontal scroll and tell the parent layout
            // "Hey parent bro! im scrolling horizontally, this has nothing to do with ur scrollview so stop capturing my event and stay the f*** where u are "
            if(xVelocityABS > yVelocityABS){
                //  So, we'll disallow the parent to listen to any touch events until i have moved my fingers off the screen
                parent.requestDisallowInterceptTouchEvent(true)
            }
        } else if (event?.action == MotionEvent.ACTION_CANCEL || event?.action == MotionEvent.ACTION_UP){
            // If the touch event has been cancelled or the finger is off the screen then reset it (i.e let the parent capture the touch events on webview as well)
            parent.requestDisallowInterceptTouchEvent(false)
        }
        return super.onTouchEvent(event)
    }
}

在这里,ViewThatYouWannaScrollHorizontally是您想要水平滚动的视图,当您水平滚动时,您不希望垂直滚动条捕捉触摸并认为“哦!用户正在垂直滚动,所以 parent.requestDisallowInterceptTouchEvent(true)基本上会说垂直滚动条”嘿你!不要捕获任何触摸,因为用户正在水平滚动“

在用户完成水平滚动并尝试通过放置在垂直滚动条内的水平滚动条垂直滚动之后,它会看到 Y 轴上的触摸速度大于 X 轴,这表明用户没有水平滚动并且水平滚动的东西会说“嘿你!父母,你听到我了吗?..用户正在垂直滚动我,现在你可以拦截触摸并在垂直滚动中显示我下方的东西”

于 2021-05-12T11:40:36.830 回答