Get button coordinates and detect if finger is over them - Android

前端 未结 4 1374
迷失自我
迷失自我 2020-11-30 07:58

I have 4 buttons in my android app activity. This is what it looks like:

As yo

4条回答
  •  情书的邮戳
    2020-11-30 08:54

    getX() getY() for a OnTouchListener give coordinates relative the the cooresponding view.

    If you prefer screen coordinates instead you can use one of the following

    • overwrite onTouchEvent for the activity and remove OnTouchListener-s for buttons, in which case MotionEvent will report screen coordinates instead of Button coordinates

         @Override 
         public boolean onTouchEvent (MotionEvent event) {
             xcordview.setText(String.valueOf(event.getX()));
             ycordview.setText(String.valueOf(event.getY()));
             return true;
         }
      
    • use getTop() getLeft() in OnTouchListener for a button:

        touchview.setOnTouchListener(new View.OnTouchListener() {
          @Override
          public boolean onTouch(View v, MotionEvent event) {
              xcordview.setText(String.valueOf(event.getX()+v.getLeft()));
              ycordview.setText(String.valueOf(event.getY()+v.getTop()));
              return true;
          }
      });
      

    You may consider using GestureDetector to detect swipes, however it isn't really necessary.

提交回复
热议问题