如果用户将手指移开按钮,则按取消按钮 [英] Cancel button press if user moves finger off button
问题描述
这是我在TouchListener上非常标准的按钮:
Here is my very standard button onTouchListener:
b.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN) {
b.setPressed(true);
}
if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP) {
b.setPressed(false);
// Do the button action stuff here
}
return true;
}
});
当用户按下按钮时,我会将按钮设置为按下".当用户抬起手指时,我将按钮设置为未按下",然后执行按钮应该执行的操作.
When the user presses down on the button I set the button to "pressed". When the user lifts the finger I set the button to "not pressed" and then do the stuff the button is supposed to do.
这一切都很好,除了用户按下按钮,然后在继续保持手指按下的同时,将手指移到按钮区域之外的情况下,一切都很好.抬起手指时,ACTION_UP东西仍会运行.我希望这种行为充当按钮按下的取消".因此,一旦被按下的手指移到按钮区域之外,我想b.setPressed(false);
,然后在举起手指时不做按钮动作.
This is all great except for the case where the user presses the button and then, while continuing to keep the finger down, moves the finger outside of the button area. When the finger is lifted the ACTION_UP stuff runs anyway. I would like for this behavior to act as a "cancel" of the button press. So, as soon as the pressed finger moves outside the button area I'd like to b.setPressed(false);
and then NOT do the button action stuff when the finger is raised.
我尝试使用MotionEvent.ACTION_CANCEL
和MotionEvent.ACTION_OUTSIDE
(如
I've tried using MotionEvent.ACTION_CANCEL
and MotionEvent.ACTION_OUTSIDE
(as suggested by How to detect when finger slides off the ImageButton?) but I must be missing something because they're not working.
从在用户离开时检测Android 中的按钮,似乎可以通过event.getX()
和event.getY()
完成此操作.如果getX()为负数,则位于左侧,如果getY()为负数,则位于顶部,但是要弄清楚是右侧还是底部,则必须确定尺寸按钮,然后...必须有一种更简单的方法.有吗?
From Detect when a user moves off of a button in Android it would appear that this can be done with event.getX()
and event.getY()
. If getX() is negative you're off the left and if getY() is negative you're off the top, but to figure out if you're off the right or bottom I'll have to figure out the size of the button and then... there has to be a simpler way. Is there?
推荐答案
您的回答正确.使用getWidth()
和getHeight()
来获取宽度和高度,并检查x或y是否更大.
You had the right answer. Use getWidth()
and getHeight()
to get the width and height and check if x or y is greater.
ACTION_CANCEL
不起作用,因为CANCEL
是在父视图控制触摸事件时生成的,就像ListView
在滚动时一样.
ACTION_CANCEL
doesn't work because CANCEL
is generated when a parent view takes control of the touch events, like a ListView
does when scrolling.
ACTION_OUTSIDE
仅在您请求的某些特殊情况下发生.它不会仅仅为普通的MOVE
或UP
生成.
ACTION_OUTSIDE
only happens in some unusual cases where you request it. It isn't going to be generated for just a normal MOVE
or UP
.
这篇关于如果用户将手指移开按钮,则按取消按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!