Android - Movable/Draggable Floating Action Button (FAB)

后端 未结 9 1664
温柔的废话
温柔的废话 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:26

    you can try like below by just impletementing onTouch on any View,

    xml

    
    
        
    
    
    

    java

    public class dragativity extends AppCompatActivity implements View.OnTouchListener{
    
        FloatingActionButton fab;
    
        FrameLayout rootlayout;
    
         int _xDelta;
         int _yDelta;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.drag);
    
            rootlayout = (FrameLayout) findViewById(R.id.rootlayout);
    
            fab = (FloatingActionButton) findViewById(R.id.fab);
    
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(150, 150);
            fab.setLayoutParams(layoutParams);
            fab.setOnTouchListener(dragativity.this);
        }
    
        public boolean onTouch(View view, MotionEvent event) {
            final int X = (int) event.getRawX();
            final int Y = (int) event.getRawY();
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN:
                    FrameLayout.LayoutParams lParams = (FrameLayout.LayoutParams) view.getLayoutParams();
                    _xDelta = X - lParams.leftMargin;
                    _yDelta = Y - lParams.topMargin;
                    break;
                case MotionEvent.ACTION_UP:
                    break;
                case MotionEvent.ACTION_POINTER_DOWN:
                    break;
                case MotionEvent.ACTION_POINTER_UP:
                    break;
                case MotionEvent.ACTION_MOVE:
                    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) view
                            .getLayoutParams();
                    layoutParams.leftMargin = X - _xDelta;
                    layoutParams.topMargin = Y - _yDelta;
                    layoutParams.rightMargin = -250;
                    layoutParams.bottomMargin = -250;
                    view.setLayoutParams(layoutParams);
                    break;
            }
            rootlayout.invalidate();
            return true;
        }
    
    
    }
    

提交回复
热议问题