1

Image showing intended result

Is there a way to stop the center point of a view from dragging off the screen using onTouch move events?

I can detect the point but I need the logic to stop the view moving and then re-joining the drag when the user swipes backwards. Setting a boolean will disable the move events which is no good, and setting the view back to a known good point is jumpy.

There are no answers anywhere on this so I'm wondering if it is even possible...

1 Answers1

2

You can use this to make your view restricted to the screen boundaries.

int width=v.getLayoutParams().width;;
    int height=v.getLayoutParams().height;
    switch (event.getAction()) {

        case MotionEvent.ACTION_DOWN:

            dX = v.getX() - event.getRawX();
            dY = v.getY() - event.getRawY();

            return true;

        case MotionEvent.ACTION_MOVE:

            if (width == windowWidth && height == windowHeight){}
            else {
                v.animate()
                        .x(event.getRawX() + dX)
                        .y(event.getRawY() + dY)
                        .setDuration(0)
                        .start();

                if (event.getRawX() + dX + width > windowWidth) {
                    v.animate()
                            .x(windowWidth - width)
                            .setDuration(0)
                            .start();
                }
                if (event.getRawX() + dX < 0) {
                    v.animate()
                            .x(0)
                            .setDuration(0)
                            .start();
                }
                if (event.getRawY() + dY + height > windowHeight) {
                    v.animate()
                            .y(windowHeight - height)
                            .setDuration(0)
                            .start();
                }
                if (event.getRawY() + dY < 0) {
                    v.animate()
                            .y(0)
                            .setDuration(0)
                            .start();
                }

                return true;
            }

where v is the view in onTouchListener

Anmol317
  • 1,356
  • 1
  • 14
  • 31
  • This is half way there when implemented with my code however the view only moves down and right. I need it to move top and left too, any ideas how to adapt this or where I'm going wrong? – Ashley Lidgett Jul 19 '17 at 18:00
  • please upload the full code over here which you are using to move, because this code is working for me perfectly. – Anmol317 Jul 19 '17 at 18:03
  • Ok, you are correct your code is good. I have created a custom view which off sets a few dimensions as well as moving the layout upon creation. This is why nothing has been working well for me, however after a lot of trial and error on moving margins I have finally got to where I need to be. Thank you Anmol for your help, it's much appreciated! – Ashley Lidgett Jul 19 '17 at 18:51