Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

android - How can I set any view to the middle of my touch position?

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...