0

I'm using this code to move a button. movement is happening but the button is sliding down a little bit when start moving. I'm also changing the color of the button when touched.

public boolean onTouch(View view, MotionEvent event) {
        float currX,currY;
        int action = event.getAction();

        Button gvup = (Button)findViewById(R.id.giveup);
        gvup.setBackground(getResources().getDrawable(R.drawable.btn));

        switch (action ) {
            case MotionEvent.ACTION_DOWN: {
                startClickTime = Calendar.getInstance().getTimeInMillis();
                mPrevX = event.getX();
                mPrevY = event.getY();
                gvup.setBackground(getResources().getDrawable(R.drawable.btn1));
                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);
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
                view.setLayoutParams(layoutParams);
                gvup.setBackground(getResources().getDrawable(R.drawable.btn1));
                break;
            }
            case MotionEvent.ACTION_CANCEL:
                gvup.setBackground(getResources().getDrawable(R.drawable.btn1));
                break;
            case MotionEvent.ACTION_UP:
                long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
                if(clickDuration < MAX_CLICK_DURATION) {
                    //click event has occurred
                    gvup.setBackground(getResources().getDrawable(R.drawable.btn));
                    giveUp();
                }
                break;
        }
        return true;
    }
}

The code should work perfectly but is not working. if in place of

mPrevY = event.getY();

I type

mPrevY = event.getY() + 65;

The position of movement is working fine for many mobile but not all and also not for tabs.

Thanks.

Sourav Roy
  • 323
  • 4
  • 12

1 Answers1

0

try using event.getRawY() , event.getRawX() instead of event.getY() , event.getX() in your ACTION_DOWN too.

Wukash
  • 666
  • 5
  • 9
  • when I start moving it now it is jumping off to the upper corner – Sourav Roy Mar 18 '16 at 21:26
  • What do you mean? Anyway, if you want to just move the button, you shouldn't change margins. Use `view.setX((int)(currX - mPrevX)` and `view.setY((int)(currY - mPrevY)` – Wukash Mar 18 '16 at 21:27
  • ok this is fine i mean better but not perfect... a little bit sliding downwards is still there, negligible in tab but understandable in mobile. – Sourav Roy Mar 18 '16 at 21:40