Android上拖放按钮的问题

时间:2015-04-23 19:01:56

标签: android drag-and-drop

我希望能够在用户拖动按钮时移动按钮。我正在使用API​​级别11中引入的拖放API,它有点工作。这是代码:

    public class MainActivity extends Activity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_test);

            final Button button = (Button) findViewById(R.id.button);

            button.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_STARTED:
                            button.setVisibility(View.INVISIBLE);
                            break;

                        case DragEvent.ACTION_DROP:
                            button.setY(event.getY() - button.getHeight() / 2.F);
                            button.setX(event.getX() - button.getWidth() / 2.F);
                            break;

                        case DragEvent.ACTION_DRAG_ENDED:
                            button.setVisibility(View.VISIBLE);
                            break;
                    }

                    return true;
                }
            });
        }
    }

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        android:id="@+id/test_main_layout"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/edit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/edit"
            android:text="Some text"/>

    </RelativeLayout>

目前的行为是,当用户按住按钮时,它会消失,并且它的阴影会消失。出现并被拖走。然后,当完成拖动时,阴影将被真实按钮替换。

它的工作方式有两个问题:

  1. 当用户停止拖动时,它有一个不好看的闪烁?看起来很短的时候阴影消失了,真正的按钮还没有显示出来。有可能以某种方式摆脱它吗?

  2. 当EditText具有焦点时,行为会发生变化。只需将XML中的TextView更改为EditText即可重现它。通过此更改,拖动阴影时原始按钮不会消失,两者都可见!为什么这样以及如何解决这个问题?

  3. 我在两个设备上测试它,一个用5.0.1,另一个用5.1,行为一致(两个问题)。

0 个答案:

没有答案