检查按钮离开,Android

Check Button Leave, Android

问题来了...

我尝试做的事情:

我的 Fragment 中有一个按钮,用户按下它。

而且我想知道用户的手指何时移出按钮。

我做了什么:

private Button btn;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ...

    btn = (Button) view.findViewById(R.id.btn);
    btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                // TODO do something
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                checkIfFingerStillOnButton(event);
            }
            return true;
        }
    });
}

public void checkIfFingerStillOnButton(MotionEvent event) {
    boolean result = false;

    // Button limits
    float coordLeft = btn.getLeft();
    float coordRight = btn.getRight();
    float coordTop = btn.getTop();
    float coordBot = btn.getBottom();

    // Finger coordinates
    float X = event.getX();
    float Y = event.getY();

    if (X>coordLeft && X<coordRight && Y<coordTop && Y>coordBot) { result = true; }
}

到目前为止的结果:

这些函数返回的坐标不是我所期望的。

这是单击按钮中间时得到的结果:

Left=312.0, Right=672.0, Top=670.0, Bottom=1030.0, 
X=189.0, Y=194.17029 | result=false

感谢您的帮助!

首先,你上次考试错了。 你必须做这个比较:

X>coordLeft && X<coordRight && Y>coordTop && Y<coordBot

其次,我认为坐标是相对于按钮而不是片段的。 尝试使用 getRawX()getRawY() 作为与您的设备相关的值。

我是这样解决的:

boolean result = false;
int[] location  = new int[2];
btnStartGame.getLocationOnScreen(location);

// Finger coordinates
float X = event.getRawX();
float Y = event.getRawY();

// Button limits
float coordLeft = location[0];
float coordRight = location[0] + btnStartGame.getWidth();
float coordTop = location[1];
float coordBot = location[1] + btnStartGame.getHeight();

if (X>coordLeft && X<coordRight && Y>coordTop && Y<coordBot) {
    result = true;
    btnStartGame.setText("true");
} else {
    btnStartGame.setText("false");
}

希望对其他人有所帮助。