Android: custom view onClickEvent with X & Y locations

后端 未结 6 649
你的背包
你的背包 2020-12-21 15:12

I\'ve got a custom view and I want to get the X and Y coordinates of a user click. I\'ve found that I can only get the coordinates from the onTouchEvent and an onClickEvent

6条回答
  •  情书的邮戳
    2020-12-21 15:56

    You should use GestureDetector. Subclass GestureDetector.SimpleOnGestureListener and override onDown(MotionEvent event) method to return true. Then override onSingleTapConfirmed. Pass the listener to the GestureDetector constructor. Then call setOnDoubleTapListener with that listener as a parameter:

    // in your view class constructor
    GestureDetector.SimpleOnGestureListener listener = new GestureDetector.SimpleOnGestureListener() {
       @Override
       public boolean onDown(MotionEvent e) {
          return true;
       }
       @Override
       public boolean onSingleTapConfirmed(MotionEvent e) {
          // do whatever you want
          return true;
       }
    };
    mDetector = new GestureDetector(getContext(), listener);
    mDetector.setOnDoubleTapListener(listener);
    

    Then, you can pass MotionEvents to the detector:

    @Override
    public boolean onTouchEvent(MotionEvent event) {
       return mDetector.onTouchEvent(event);
    }
    

提交回复
热议问题