Android - Movable/Draggable Floating Action Button (FAB)

后端 未结 9 1657
温柔的废话
温柔的废话 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条回答
  •  萌比男神i
    2020-12-28 15:28

    This is the listener that worked for me, with a tolerance of 70.

    private class FloatingOnTouchListener implements View.OnTouchListener {
            private float x;
            private float y;
            private float nowX;
            private float nowY;
            private float downX;
            private float downY;
            private final int tolerance = 70;
    
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    x = (int) event.getRawX();
                    y = (int) event.getRawY();
                    downX = x;
                    downY = y;
                } else
                if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    nowX = event.getRawX();
                    nowY = event.getRawY();
                    float movedX = nowX - x;
                    float movedY = nowY - y;
                    x = nowX;
                    y = nowY;
                    iconViewLayoutParams.x = iconViewLayoutParams.x + (int) movedX;
                    iconViewLayoutParams.y = iconViewLayoutParams.y + (int) movedY;
                    windowManager.updateViewLayout(view, iconViewLayoutParams);
                } else
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    float dx = Math.abs(nowX - downX);
                    float dy = Math.abs(nowY - downY);
                    if (dx < tolerance && dy < tolerance) {
                        Log.d(TAG, "clicou");
                        Log.d(TAG, "dx " + dx);
                        Log.d(TAG, "dy " + dy);
                        windowManager.removeViewImmediate(iconView);
                        windowManager.addView(displayView, layoutParams);
                    } else {
                        Log.d(TAG, "dx " + dx);
                        Log.d(TAG, "dy " + dy);
                        return true;
                    }
                }
                return true;
            }
        }
    

提交回复
热议问题