0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Drunken Daddy
  • 7,326
  • 14
  • 70
  • 104

2 Answers2

1
 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

Ara Hakobyan
  • 1,682
  • 1
  • 10
  • 21
0

I was facing the same issue but an important point to note is that you will get 0 until Android lays & renders out the view on the screen.

The proper way is by adding an observer to your view & then setting the position this way

 yourView.getViewTreeObserver().addOnGlobalLayoutListener(
            new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    top2AxOriginXCoordinate = top2AX.getX();
                    top2AxOriginYCoordinate = top2AX.getY();

                    // Remove the listener afterwards
                    yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            });
Oush
  • 3,090
  • 23
  • 22