0

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;
    }
}
Dhruv
  • 1,862
  • 3
  • 20
  • 38
Uma Achanta
  • 3,669
  • 4
  • 22
  • 49
  • pseudocode: `int width = btn.getWidth(); int height = btn.getHeight(); int x = touchEvent.getScreenX(); int y = touchEvent.getScreenY(); btn.moveTo(Math.max(Math.min(SCREEN_MAX_WIDTH - width,x-width/2),0),Math.max(Math.min(SCREEN_MAX_HEIGHT - height,y-height/2),0));` – DimXenon Jun 17 '16 at 12:31
  • I didnot get where to write this. could you please answer clearly – Uma Achanta Jun 18 '16 at 10:08

0 Answers0