I am using a FloatingActionButton in my app. Occasionally, it overlaps essential content, so I would like to make it so the user can drag the FAB out of the way.
No
All proposed answers used OnTouch listener, which is not recommended by recent Android API because of the Accessibility implementations. Note also that startDrag() method is obsolete. Developers shoud use startDragAndDrop() instead. My implementation uses OnDragListener() as follows:
Put the below snippet inside onCreatView() method, where root is root view, taken by the inflater (or any other view, which can receive Drop events);
final FloatingActionButton fab = root.findViewById(R.id.my_fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Do whatever this button will do on click event
}
});
root.setOnDragListener(new View.OnDragListener() {
@Override
public boolean onDrag(View v, DragEvent event) {
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_LOCATION:
dX = event.getX();
dY = event.getY();
break;
case DragEvent.ACTION_DRAG_ENDED:
fab.setX(dX-fab.getWidth()/2);
fab.setY(dY-fab.getHeight()/2);
break;
}
return true;
}
});
fab.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
View.DragShadowBuilder myShadow = new View.DragShadowBuilder(fab);
v.startDragAndDrop(null, myShadow, null, View.DRAG_FLAG_GLOBAL);
return true;
}
});