取消触摸事件对接



我正在编写一个非常简单的应用程序,具有以下场景:

1)屏幕A3个按钮可以在其他屏幕上移动。

2)现在,如果我按住一个按钮(例如按钮1)并快速单击其他按钮,那么它将启动其他屏幕的多个实例。我认为这不应该发生。如何防止这种情况。

3)而且更奇怪。移动到其他屏幕后,如果我不释放屏幕A上的按钮1,那么即使我可以看到第二个屏幕,它仍然允许对屏幕A的其余两个按钮执行单击

在这里很明显启动第二个屏幕,但仍然第一个屏幕按钮事件起作用。任何想法都可以避免这种情况。

启用 1 时如何禁用其他按钮,这是一个算法问题。您可以尝试在活动中创建布尔值或控制变量(然后将活动的最终引用传递到需要它的任何位置),或者在静态上下文中创建。但是要回答问题的标题 - 您可以通过添加OnTouchListener来"取消触摸事件",或者如果您正在扩展类 Button,则可以覆盖onTouchEvent(MotionEvent ev)方法。

使用 OnTouchListener 将禁用任何以前定义的触摸事件行为。可以通过从按钮调用方法从内部调用实际performClick单击事件。

//in order to use button inside OnTouchEvent, its reference must be final
//if it's not, create a new final reference to your button, like this:
final finalButton = button;
button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        // ... additional code if necessary
        if(canBeClicked) {
            finalButton.performClick();
            return true;
        }
        else return false;
    }
}

在扩展按钮的类中重写 onTouchEvent 应该看起来像这样。

@Override
public boolean onTouchEvent(MotionEvent ev) {
    // ... additional code if necessary
    //here we don't really need to call performClick(), although API recommends it
    //we just send the touch event to the super-class and let it handle the situation.
    if(activity.canBeClicked) return super.onTouchEvent(ev);
    else return false;
}

我发现的一种解决方案是在 onPause() 中禁用单击侦听器并在 onResume() 中启用它。我们能在这方面得到更好的支持吗?

最新更新