从Android gridView拖放所选项目

时间:2016-04-08 08:40:57

标签: android gridview drag-and-drop

我想从gridView中拖动一个项目并将其放在线性布局中。我可以拖动整个列表,但不仅仅是所选项目。

listArtifactView.setOnTouchListener(new MyTouchListener());
findViewById(R.id.zep_layout).setOnDragListener(new MyDragListener());

MyTouchListener类:

public class MyTouchListener implements View.OnTouchListener {
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
            ClipData data = ClipData.newPlainText("", "");
            View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
            view.startDrag(data, shadowBuilder, view, 0);
            view.setVisibility(View.INVISIBLE);
            return true;
        } else {
            return false;
        }
    }
}

MyDragListener类:

public class MyDragListener implements View.OnDragListener {

    @Override
    public boolean onDrag(View v, DragEvent event) {
        int action = event.getAction();
        switch (event.getAction()) {
            case DragEvent.ACTION_DRAG_STARTED:
                // do nothing
                break;
            case DragEvent.ACTION_DRAG_ENTERED:
                v.setBackgroundColor(Color.parseColor("#aaaaaa"));
                break;
            case DragEvent.ACTION_DRAG_EXITED:
                v.setBackgroundColor(Color.parseColor("Color.GREEN"));
                break;
            case DragEvent.ACTION_DROP:
                // Dropped, reassign View to ViewGroup
                View view = (View) event.getLocalState();
                ViewGroup owner = (ViewGroup) view.getParent();
                owner.removeView(view);
                LinearLayout container = (LinearLayout) v;
                container.addView(view);
                view.setVisibility(View.VISIBLE);
                break;
            case DragEvent.ACTION_DRAG_ENDED:
                v.setBackgroundColor(Color.GREEN);
            default:
                break;
        }
        return true;
    }
}

当我使用getChildAt时,应用程序崩溃了。如何仅对列表中的选定项目执行拖放操作?

0 个答案:

没有答案