0

I am on Android Lollipop (minSdk=21), and want to implement moving a Floating Action Button around with a dragging gesture. The button is a custom subclass of ImageButton, the code is described here so I won't repeat it: Define default values for layout_width and layout_height properties for a subclass in a style

For dragging, I use the way described here: http://developer.android.com/guide/topics/ui/drag-drop.html. Here is what my code looks like:

    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;
        }
    });

Generally, it works, but the problem is the 'drag shadow': it is square. For this reason or the other, it doesn't respect the oval outline of the FAB.

How can I make it behave correctly?

4

2 回答 2

1

@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>

拖动阴影现在完美运行。

谢谢你成为我的橡皮鸭

于 2015-02-23T18:38:38.240 回答
1

我建议实现您自己的子类DragShadowBuilder:仅覆盖onDrawShadow()并绘制 FAB 具有的大小的圆。然后只需在startDrag().

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

于 2015-02-23T18:02:29.850 回答