Search code examples
androidtouch-eventontouch

Android stop drag out of screen from center point of View


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...


Solution

  • 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