I'm using this code to move a button in the screen but when I reach the sides it is moving out of the screens.
private float mPrezX, mPrevY;
private static final int MAX_CLICK_DURATION = 200;
private long startClickTime;
@Override
public boolean onTouch(View view, MotionEvent event) {
int action = event.getActionMasked();
Button gvup = (Button)findViewById(R.id.giveup);
gvup.setBackground(getResources().getDrawable(R.drawable.btn));
switch (action ) {
case MotionEvent.ACTION_DOWN: {
mPrevX = view.getX() - event.getRawX();
mPrevY = view.getY() - event.getRawY();
startClickTime = Calendar.getInstance().getTimeInMillis();//!!
gvup.setBackground(getResources().getDrawable(R.drawable.btn1));
break;
}
case MotionEvent.ACTION_MOVE:
{
view.animate()
.x(event.getRawX() + mPrevX)
.y(event.getRawY() + mPrevY)
.setDuration(0)
.start();
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;
}
I'm also changing its background color if pressed and also made it clickable.
I need to keep that button inside the layout.
I have also tried this and this links but both of these approaches leading to squeeze the button when moved to the sides.
Please help. Thanks in advance.