【问题标题】:Capturing touch events in an android list item and prevent scrolling在android列表项中捕获触摸事件并防止滚动
【发布时间】:2012-06-10 02:04:37
【问题描述】:

我在这里尝试了一个疯狂的想法,将自定义控件放在某个列表视图的项目中。只有当用户按下某个触发点然后他们可以“拖动”时,该控件才会“激活”。

我的问题是,我可以在 onTouchEvent(...) 中做什么来防止列表视图接收事件和滚动。现在我可以触摸并获得控件,但是如果我将手指向上或向下移动太多,列表视图会接管并开始滚动,那么我的视图甚至不会收到 ACTION_UP 事件。

这是我当前的 onTouchEvent 代码:

if (e.getAction() == MotionEvent.ACTION_DOWN) {

    Log.d("SwipeView", "onTouchEvent - ACTION_DOWN" + e.getX() + " " + e.getY());           
    int midX = (int)(this.getWidth() / 2);
    int midY = (int)(this.getHeight() / 2);

    if (Math.abs(e.getX() - midX) < 100 &&
        Math.abs(e.getY() - midY) < 100) {

        Log.d("SwipeView", "HEY");
        setDragActive(true);

    }

    this.invalidate();
    return true;

} else if (e.getAction() == MotionEvent.ACTION_MOVE) {

    _current[0] = e.getX();
    _current[1] = e.getY();

    this.invalidate();
    return true;

} else if (e.getAction() == MotionEvent.ACTION_UP) {

    _current[0] = 0;
    _current[1] = 0;

    setDragActive(false);

    this.invalidate();
    return true;

}

我确信它以某种方式与事件层次结构有关。

【问题讨论】:

    标签: android events custom-controls touch android-event


    【解决方案1】:

    这可能不是您想要的,但可以在您的活动中实现捕获功能。添加

    private View capturedView;
    public void setCapturedView(View view) { this.capturedView = view); }
    
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        return (this.capturedView != null) ?
            this.capturedView.dispatchTouchEvent(event) :
            super.dispatchTouchEvent(event);
    }
    

    到您的活动,然后只需将您的观点传递给ACTION_DOWN,并将空值传递给ACTION_UP。它并不完全漂亮,但它确实有效。不过,我确信有一种适当的方法可以做到这一点。

    【讨论】:

      【解决方案2】:

      终于学会了正确的做法:requestDisallowInterceptTouchEvent

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-31
        • 2020-10-03
        • 1970-01-01
        • 2014-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多