Android - Movable/Draggable Floating Action Button (FAB)

后端 未结 9 1663
温柔的废话
温柔的废话 2020-12-28 14:47

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

9条回答
  •  死守一世寂寞
    2020-12-28 15:33

    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:

    1. Define two global float variables dX and dY;
    2. 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;
          }
      });
      

提交回复
热议问题