Issue
I want to touch drag a view all around the screen and on touch release I want to bring the view back to its origin position.
Here's my code:
private float xCoOrdinate, yCoOrdinate;
private float top2AxOriginXCoordinate, top2AxOriginYCoordinate;
private void initControls(View view) {
top2AX = view.findViewById(R.id.top2AX);
top2AxOriginXCoordinate = top2AX.getX();
top2AxOriginYCoordinate = top2AX.getY();
addDragListener();
}
private void addDragListener() {
myView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
xCoOrdinate = view.getX() - event.getRawX();
yCoOrdinate = view.getY() - event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
view.animate().x(event.getRawX() + xCoOrdinate).y(event.getRawY() + yCoOrdinate).setDuration(0).start();
break;
case MotionEvent.ACTION_UP:
view.animate().x(top2AxOriginXCoordinate).y(top2AxOriginYCoordinate).setDuration(500).start();
break;
default:
return false;
}
return true;
}
});
}
The touch and drag is working perfectly, but when I release touch its not coming back to its origin position. It goes to the top left of the screen with a slight left margin. What am I doing wrong here?
Solution
top2AxOriginXCoordinate = top2AX.getX();
top2AxOriginYCoordinate = top2AX.getY();
may be this two variables are 0.0 , if it's so then told me I'll help you
Answered By - Ara Hakobyan
Answer Checked By - Candace Johnson (JavaFixing Volunteer)