1

How can I set any view to the middle of my touch position using onTouchEvent?

Red Circle Is My Click Position

Black Circle Is The View Like Button, ImageView, And So On...

enter image description here

Can someone leave an example?

Edit

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_MOVE) {
        imgCircle.setX(event.getX() - imgCircle.getWidth() / 2);
        imgCircle.setY(event.getY() - imgCircle.getHeight() / 2);
    }
    return false;
}
Taha Sami
  • 1,565
  • 1
  • 16
  • 43

1 Answers1

1

Example of a solution:

@Override
public boolean onTouchEvent(MotionEvent event) {
    float x = event.getX();
    float y = event.getY();
    yourView.setX(x);
    yourView.setY(y);
    return false;
}

You get the coordinates from click and set them to the view. If you have multiple views inside of one you might have to get relative position of the parent view and then subtract the clicked position from parent position.

If you want to set the view position to the centre just subract half of view width from x and half of height from y.

EDIT

How to set position to centre of view:

yourView.setX(x-yourView.getWidth()/2);
yourView.setY(y-yourView.getHeight()/2);
UrbanR
  • 202
  • 1
  • 10
  • About this code, I already tested it before but not like what I want in the image above. – Taha Sami Jan 05 '21 at 13:44
  • If you want to set the view position to the center just subtract half of view width from x and half of height from y. - How can I do that? – Taha Sami Jan 05 '21 at 13:45
  • @K921 added and edit to my post where i explain that better. – UrbanR Jan 05 '21 at 13:48
  • Can you explain what exactly is not working? – UrbanR Jan 05 '21 at 14:03
  • When I touch the screen, The Image comes under my finger, not in the middle. – Taha Sami Jan 05 '21 at 14:06
  • The width became in middle but height still under my finger when I touch. – Taha Sami Jan 05 '21 at 14:13
  • I don't have any acces to any device right now, so i can't test anything. Maybe the problem is in the parent layout offset. Try to follow code like here: https://stackoverflow.com/a/39588899/13121971 and inside the onTouch() just paste the same code u already have in your onTouch. – UrbanR Jan 05 '21 at 14:16
  • It's working when I change it to / 1 about the height – Taha Sami Jan 05 '21 at 15:29