0

I have a layout which contains text and wraps it. I need to move this layout vertically on the screen.

This is what I do.

View valuesContainer = view.findViewById(R.id.valuesContainer);
valuesContainer.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) v.getLayoutParams();
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    oldY = (int)event.getRawY();
                    initialTopMargin = params.topMargin;
                    break;
                case MotionEvent.ACTION_MOVE:
                    newY = (int)event.getY();
                    params.topMargin = (int) (initialTopMargin - (oldY - newY));
                    v.setLayoutParams(params);
                    }
                    break;
            }
            return true;
        }
    });

This moves the layout vertically on the screen. But now, I need this layout to go back to it's original place when I quit the finger of the screen.

Any code would be appriciated

Maveňツ
  • 1
  • 12
  • 50
  • 89
masmic
  • 3,526
  • 11
  • 52
  • 105

3 Answers3

2

Try this:

case MotionEvent.ACTION_UP:
     params.topMargin = initialTopMargin;
     v.setLayoutParams(params);
Misagh Emamverdi
  • 3,654
  • 5
  • 33
  • 57
2

Use ACTION_UP to move the layout back to its original position. Below is the code. Try it.

View valuesContainer = view.findViewById(R.id.valuesContainer);

valuesContainer.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) v.getLayoutParams();
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    oldY = (int)event.getRawY();
                    initialTopMargin = params.topMargin;
                    break;
                case MotionEvent.ACTION_MOVE:
                    newY = (int)event.getY();
                    params.topMargin = (int) (initialTopMargin - (oldY - newY));
                    v.setLayoutParams(params);
                    break;
               case MotionEvent.ACTION_UP:
                    params.topMargin = initialTopMargin;
                    v.setLayoutParams(params);
                    break;
            }
            return true;
        }
    });
CSchulz
  • 10,882
  • 11
  • 60
  • 114
1

Store the initial pos when you get the ACTION_DOWN event. Handle the ACTION_UP event and, in there, set it to top again. If you want it to be smooth, launch a new thread updating the value and waiting or something.

eduyayo
  • 2,020
  • 2
  • 15
  • 35