android - 触摸时 ACTION_CANCEL

标签 android events view touch

我有以下类,它代表一个可触摸的 View 并绘制一个滑动条。

public class SlideBar extends View {
private int progress;
private int max;

private Paint background;
private Paint upground;

private RectF bar;

private boolean firstDraw;

public SlideBar(Context context, AttributeSet attrs) {
    super(context, attrs);
    progress = 0;

    upground = new Paint();
    upground.setColor(Color.parseColor("#C2296C"));

    background = new Paint();
    background.setColor(Color.parseColor("#777777"));
}

private void onFirstDraw() {
    max = getWidth();
    bar = new RectF(0, 19, max, 21);
}

public void onDraw(Canvas canvas) {
    if (!firstDraw) {
        onFirstDraw();
        progress = max;
        firstDraw = true;
    }

    canvas.save();
    canvas.drawRoundRect(bar, 5, 5, background);
    canvas.drawCircle(progress, 20, 9, upground);
    canvas.restore();
}

public void setValue(int value) {
    progress = value;
}

public boolean onTouchEvent(MotionEvent evt) {
    System.out.println(evt.getAction());
    progress = (int) evt.getX();
    invalidate();
    return false;
}
}

但是当触摸和拖动它时,我收到一个 ACTION_DOWN,然后一些 ACTION_MOVE 收到一个 ACTION_CANCEL 并且没有其他事件。

为什么会这样?我不想取消该事件并使其保持拖动条。

最佳答案

这将在父容器拦截您的触摸事件时发生。任何覆盖 ViewGroup.onInterceptTouchEvent(MotionEvent) 的 ViewGroup可以做到这一点(例如 ScrollView 或 ListView)。

处理此问题的正确方法是调用 ViewParent.requestDisallowInterceptTouchEvent(boolean)一旦您认为需要保留 Action 事件,就在您的父 View 上使用方法。

这是一个简单的例子(attemptClaimDrag 方法取自android源代码):

/**
 * Tries to claim the user's drag motion, and requests disallowing any
 * ancestors from stealing events in the drag.
 */
private void attemptClaimDrag() {
    //mParent = getParent();
    if (mParent != null) {
        mParent.requestDisallowInterceptTouchEvent(true);
    }
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        if (iWantToKeepThisEventForMyself(event)) {
            attemptClaimDrag();
        }
        //your logic here
    } else {
        //your logic here
    }
}

关于android - 触摸时 ACTION_CANCEL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6018309/

相关文章:

android - 在三星设备上播放 mp4 文件时出现 PVMFErrContentInvalidForProgressivePlayback 错误

java - 用于 Espresso 测试的 Android Studio 项目设置

emacs - 在 Emacs Org 模式下执行标签搜索时消除不匹配的顶级树

c# - C#WPF MVVM DataGrid MouseBinding仅适用于行

swing - Clojure 代理 : rate limiting?

ruby-on-rails - Rails 复杂 View 表单与 has_many :through association

java - findViewById(R.id.screen) 返回 null

javascript - HTML 媒体捕获一键

android - ContactsContract API - 获取显示名称和组织名称

javascript - 等待事件发生时返回 promise 的函数