Reputation: 982
I need a FloatingActionButton (FAB) in my Activity that you can drag around. But you also can click on it. From another post I copied this:
fab.setOnTouchListener(new View.OnTouchListener() {
float startX;
int lastAction;
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
startX = view.getX() - event.getRawX();
lastAction = MotionEvent.ACTION_DOWN;
break;
case MotionEvent.ACTION_MOVE:
view.setX(event.getRawX() + startX);
lastAction = MotionEvent.ACTION_MOVE;
break;
case MotionEvent.ACTION_UP:
if (lastAction == MotionEvent.ACTION_DOWN){
edit();
}
break;
case MotionEvent.ACTION_BUTTON_PRESS:
default:
return false;
}
return true;
}
});
The problem is: If you want to click on it often it does not recognize it as a click but as a move. so this is not very precise. How can I change the code to make it better?
Upvotes: 2
Views: 1684
Reputation: 3613
check the dragged distance, if its less than 10px => the user probably didn't want to drag.
fab.setOnTouchListener(new View.OnTouchListener() {
float startX;
float startRawX;
float distanceX;
int lastAction;
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
startX = view.getX() - event.getRawX();
startRawX = event.getRawX();
lastAction = MotionEvent.ACTION_DOWN;
break;
case MotionEvent.ACTION_MOVE:
view.setX(event.getRawX() + startX);
lastAction = MotionEvent.ACTION_MOVE;
break;
case MotionEvent.ACTION_UP:
distanceX = event.getRawX()-startRawX;
if (Math.abs(distanceX)< 10){
edit();
}
break;
case MotionEvent.ACTION_BUTTON_PRESS:
default:
return false;
}
return true;
}
});
Upvotes: 1