首页 > 解决方案 > 按下按钮

问题描述

我有从类“Button”继承的类“myButton”。内部实现的方法“onTouch”,如果你按下按钮就会起作用。当您单击按钮外的任何位置时,我需要执行操作。

有什么方法可以验证触摸是在按钮之外进行的吗?

我想出了在视图(全屏)中添加触摸检查的想法。但是在这种情况下,如果您单击按钮,将激活两个事件“onTouch”:在我的类“myButton”中并单击 View。

标签: javakotlin

解决方案


如果你想处理按下按钮并释放按钮,你可以这样做

    Button button = (Button) findViewById(R.id.button);
    button.setOnTouchListener(new View.OnTouchListener() {        
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // PRESSED
                break; // if you want to handle the touch event
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL
                // RELEASED
                break; // if you want to handle the touch event
        }
        return false;
    }
});

如果按下按钮并且释放按钮并且您只想按下按钮,这将处理您可以相应地进行更改

你有 kotlin 和 java 都标记了这是 java 所以如果你想在 kotlin 中使用它,请告诉我

ps我返回false,因为如果你不这样做,你将绕过按钮的常规触摸处理。这意味着您将失去按下按钮和触摸波纹的视觉效果。此外,Button#isPressed() 将在实际按下按钮时返回 false。


推荐阅读