move floating button with in the screen height and width

329 Views Asked by At

I want to move a button with in the screen I tried following code

it is working but moving out of screen. Is it possible to restrict its movement within the screen. Also tried to get the screen height and width and set to layout height and width but no use.

public class MultiTouchListener implements View.OnTouchListener {

    private float mPrevX;
    private float mPrevY;

    public MainActivity mainActivity;

    public MultiTouchListener(MainActivity mainActivity1) {
        mainActivity = mainActivity1;
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        float currX, currY;
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN: {

                mPrevX = event.getX();
                mPrevY = event.getY();
                break;
            }

            case MotionEvent.ACTION_MOVE: {

                currX = event.getRawX();
                currY = event.getRawY();


                ViewGroup.MarginLayoutParams marginParams = new ViewGroup.MarginLayoutParams(view.getLayoutParams());
                marginParams.setMargins((int) (currX - mPrevX), (int) (currY - mPrevY), 0, 0);
                CoordinatorLayout.LayoutParams layoutParams = new CoordinatorLayout.LayoutParams(marginParams);
                view.setLayoutParams(layoutParams);


                break;
            }


            case MotionEvent.ACTION_CANCEL:
                break;

            case MotionEvent.ACTION_UP:

                break;
        }
        return true;
    }
}
0

There are 0 best solutions below