Android: Detect if user touches and drags out of button region?

前端 未结 9 2010
孤城傲影
孤城傲影 2020-12-04 16:33

In Android, how can we detect if a user touches on button and drags out of region of this button?

9条回答
  •  再見小時候
    2020-12-04 17:01

    Check the MotionEvent.MOVE_OUTSIDE: Check the MotionEvent.MOVE:

    private Rect rect;    // Variable rect to hold the bounds of the view
    
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN){
            // Construct a rect of the view's bounds
            rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
    
        }
        if(event.getAction() == MotionEvent.ACTION_MOVE){
            if(!rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())){
                // User moved outside bounds
            }
        }
        return false;
    }
    

    NOTE: If you want to target Android 4.0, a whole world of new possibilities opens: http://developer.android.com/reference/android/view/MotionEvent.html#ACTION_HOVER_ENTER

提交回复
热议问题