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

前端 未结 9 2007
孤城傲影
孤城傲影 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条回答
  •  Happy的楠姐
    2020-12-04 17:06

    view.setClickable(true);
    view.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (!v.isPressed()) {
                Log.e("onTouch", "Moved outside view!");
            }
            return false;
        }
    });
    

    view.isPressed uses view.pointInView and includes some touch slop. If you don't want slop, just copy the logic from the internal view.pointInView (which is public, but hidden so it's not a part of the official API and could disappear at any time).

    view.setClickable(true);
    view.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                v.setTag(true);
            } else {
                boolean pointInView = event.getX() >= 0 && event.getY() >= 0
                        && event.getX() < (getRight() - getLeft())
                        && event.getY() < (getBottom() - getTop());
                boolean eventInView = ((boolean) v.getTag()) && pointInView;
                Log.e("onTouch", String.format("Dragging currently in view? %b", pointInView));
                Log.e("onTouch", String.format("Dragging always in view? %b", eventInView));
                v.setTag(eventInView);
            }
            return false;
        }
    });
    

提交回复
热议问题