圆形浮动操作按钮的拖动阴影是方形的

Drag shadow is square for a round floating action button

我正在使用 Android Lollipop (minSdk=21),并希望通过拖动手势实现浮动操作按钮的移动。按钮是ImageButton的自定义子类,代码在这里就不赘述了:Define default values for layout_width and layout_height properties for a subclass in a style

对于拖动,我使用此处描述的方式:http://developer.android.com/guide/topics/ui/drag-drop.html。这是我的代码的样子:

    favoriteButton.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            v.startDrag(null, new View.DragShadowBuilder(v), null, 0);

            return true;
        }
    });

    findViewById(R.id.test_main_layout).setOnDragListener(new View.OnDragListener() {

        @Override
        public boolean onDrag(View v, DragEvent event) {
            switch (event.getAction()) {
                case DragEvent.ACTION_DRAG_ENTERED:
                    favoriteButton.setVisibility(View.INVISIBLE);
                    break;

                case DragEvent.ACTION_DROP:
                    favoriteButton.setX(event.getX() - favoriteButton.getWidth() / 2);
                    favoriteButton.setY(event.getY() - favoriteButton.getHeight() / 2);
                    favoriteButton.setVisibility(View.VISIBLE);
                    break;
            }

            return true;
        }
    });

一般来说,它可以工作,但问题是 'drag shadow':它是正方形的。由于这个或其他原因,它不符合 FAB 的椭圆形轮廓。

如何让它正常运行?

我建议实施您自己的 DragShadowBuilder 子 class: 只覆盖 onDrawShadow() 并绘制一个 FAB 大小的圆。然后只需在 startDrag() 中使用 class。

如果您的 FAB 是 ImageButton,您可能已经有了可以用作阴影的图像,这样您甚至不必画一个圆圈。您可以简单地将相同的图像绘制到 onDrawShadow() 中的 Canvas。以下是如何从图像构建阴影的示例:https://gist.github.com/MarcinGil/5337109.

@FD_ 谢谢你的回答。同时,在尝试在评论中提问时,我注意到我用于 FAB 的背景可绘制对象不是椭圆形,而是一种简单的颜色:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="?android:attr/colorControlHighlight">

    <item android:drawable="?android:attr/colorAccent"/>

</ripple>

改成这样后:

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="?android:attr/colorControlHighlight">

    <item android:drawable="@drawable/oval_accent_drawable"/>

</ripple>

使用另一个具有所需颜色的椭圆形可绘制对象:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="oval">

    <solid android:color="?android:attr/colorAccent"/>

    <size
        android:width="@dimen/fab_size"
        android:height="@dimen/fab_size"/>

</shape>

拖动阴影现在完美运行。

谢谢你做我的rubber duck