Android GridView通过拖放重新排序元素

时间:2011-08-22 11:15:40

标签: android gridview drag-and-drop

我正在处理的应用程序中有一个GridView。我希望能够通过拖放重新排序GridView中的项目。我已经为ListViews找到了很多帮助,但在GridViews上没有任何帮助。我希望在此启动器应用http://www.youtube.com/watch?v=u5LISE8BU_E&t=5m30s中实现此行为。有什么想法吗?

9 个答案:

答案 0 :(得分:23)

如果您不解决此问题,我将提供我的代码。但它适用于Android 3.0及更高版本,因为我使用android drag-n-drop framework

grid = (GridView) findViewById(R.id.grid);
grid.setAdapter(new DragGridAdapter(items, getActivity()));

....

grid.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                GridView parent = (GridView) v;

                int x = (int) event.getX();
                int y = (int) event.getY();

                int position = parent.pointToPosition(x, y);
                if (position > AdapterView.INVALID_POSITION) {

                    int count = parent.getChildCount();
                    for (int i = 0; i < count; i++) {
                        View curr = parent.getChildAt(i);
                        curr.setOnDragListener(new View.OnDragListener() {

                            @Override
                            public boolean onDrag(View v, DragEvent event) {

                                boolean result = true;
                                int action = event.getAction();
                                switch (action) {
                                case DragEvent.ACTION_DRAG_STARTED:
                                    break;
                                case DragEvent.ACTION_DRAG_LOCATION:
                                    break;
                                case DragEvent.ACTION_DRAG_ENTERED:
                                    v.setBackgroundResource(R.drawable.shape_image_view_small_gallery_selected);
                                    break;
                                case DragEvent.ACTION_DRAG_EXITED:
                                    v.setBackgroundResource(R.drawable.shape_image_view_small_gallery_unselected);
                                    break;
                                case DragEvent.ACTION_DROP:
                                    if (event.getLocalState() == v) {
                                        result = false;
                                    } else {
                                        View droped = (View) event.getLocalState();
                                        GridItem dropItem = ((DragGridItemHolder) droped.getTag()).item;

                                        GridView parent = (GridView) droped.getParent();
                                        DragGridAdapter adapter = (DragGridAdapter) parent.getAdapter();
                                        List<GridItem> items = adapter.getItems();

                                        View target = v;
                                        GridItem targetItem = ((DragGridItemHolder) target.getTag()).item;
                                        int index = items.indexOf(targetItem);
                                        items.remove(dropItem);
                                        items.add(index, dropItem);
                                        adapter.notifyDataSetChanged();
                                    }
                                    break;
                                case DragEvent.ACTION_DRAG_ENDED:
                                    v.setBackgroundResource(R.drawable.shape_image_view_small_gallery_unselected);
                                    break;
                                default:
                                    result = false;
                                    break;
                                }
                                return result;
                            }
                        });
                    }

                    int relativePosition = position - parent.getFirstVisiblePosition();


                    View target = (View) parent.getChildAt(relativePosition);

                    DragGridItemHolder holder = (DragGridItemHolder) target.getTag();
                    GridItem currentItem = holder.item;
                    String text = currentItem.getFile().getAbsolutePath();

                    ClipData data = ClipData.newPlainText("DragData", text);
                    target.startDrag(data, new View.DragShadowBuilder(target), target, 0);
                }
            }
            return false;

和DragGridAdapter

public class DragGridAdapter extends BaseAdapter{
private Context context;
private List<GridItem> items;

public DragGridAdapter(List<GridItem> items, Context context){
    this.context = context;
    this.items = items;
}

@Override
public int getCount() {
    return items.size();
}

@Override
public Object getItem(int position) {
    return items.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    DragGridItemHolder holder;
    if (convertView == null) {
        holder = new DragGridItemHolder();

        ImageView img = new ImageView(context);
        holder.image = img;
        convertView = img;
        convertView.setTag(holder);
    } else {
        holder = (DragGridItemHolder) convertView.getTag();
    }
    holder.item = items.get(position);
    holder.image.setImageBitmap(items.get(position).getBitmap());
    return convertView;
}

public List<GridItem> getItems() {
    return items;
}

我希望对你有帮助

答案 1 :(得分:7)

我的拖放网格视图版本https://github.com/askerov/DynamicGrid 它扩展了原始的GridView,支持拖放以重新排序项目,如果拖出屏幕则自动滚动。它在3.0+ api上完全正常运行,但支持2.2和2.3,但有限制(没有动画)。

答案 2 :(得分:2)

看看thquinn的DraggableGridView,这是针对Android 2.2(API级别8)开发的。 希望这有助于某人:)

答案 3 :(得分:1)

使用drag-n-drop框架,而不是循环子节点并设置draglistener,我用作网格项布局容器,一个DragableLinearLayout,它扩展了LinearLayout并实现了onDragEvent(DragEvent)方法。

所以你可以像往常一样使用适配器填充网格,大多数拖放代码都在DragableLinearLayout的onDragEvent上

public class DragableLinearLayout extends LinearLayout {


    public DragableLinearLayout(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);

    }

    public DragableLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

    }

    public DragableLinearLayout(Context context) {
        super(context);

    }

    @Override
    public boolean onDragEvent(DragEvent event) {
        //in wich grid item am I?
        GridView parent = (GridView) getParent();
        Object item = parent.getAdapter().getItem(
                parent.getPositionForView(this));
            //if you need the database id of your item...
        Cursor cur = (Cursor) item;
        long l_id = cur.getLong(cur.getColumnIndex("youritemid"));

        switch (event.getAction()) {
        case DragEvent.ACTION_DRAG_STARTED:

            return true;
        case DragEvent.ACTION_DRAG_ENTERED:

            setBackgroundColor(Color.GREEN);
            invalidate();
            return true;
        case DragEvent.ACTION_DRAG_EXITED:
            setBackgroundColor(Color.WHITE);
            invalidate();
            return false;
        case DragEvent.ACTION_DROP:
ClipData cd = event.getClipData();
            long l_id_start = Long.valueOf(cd.getItemAt(0).getText()
                    .toString());
            //
            Toast.makeText(getContext(), "DROP FROM " + l_id_start
                    + " TO " + l_id, Toast.LENGTH_LONG);
            //do your stuff  
                    ........
                    //the db requery will be on the onDragEvent.drop of the container
                    //see the listener


            return false;
        case DragEvent.ACTION_DRAG_ENDED:
            setBackgroundColor(Color.WHITE);
            invalidate();
            //
            return false;

        }

        return true;

    }


}



private View.OnDragListener listenerOnDragEvent = new View.OnDragListener() {

    public boolean onDrag(View v, DragEvent event) {
        // Defines a variable to store the action type for the incoming
        // event
        final int action = event.getAction();
        switch (action) {

        case DragEvent.ACTION_DROP:

            // REQUERY
            updateDbView();
            return false;
            // break;

        }
        return true;
    }
};

答案 4 :(得分:1)

不容易对此提供简短的答案,因为涉及数百行代码:您需要拦截拖动操作的开始,通常在onLongClick上,隐藏启动操作的视图,显示可以覆盖的内容在用户仍处于触摸操作状态时移动,最后在触摸时进行更改。最好的方法是在android.widget中扩展标准的GridView。结果如下:

enter image description here

这是一个youtube视频演示,您可能会发现它非常有用: http://www.youtube.com/watch?v=m4yktX3SWSs&feature=youtu.be

我还在我的博客上的文章中提供了更详细的答案,您可能会发现它很有用,因为它附带了完整的源代码示例。链接是:http://www.pocketmagic.net/2013/11/complex-android-gridview-with-drag-and-drop-functionality/

答案 5 :(得分:0)

我最近找到了一个解决方案,其作者在这里花了很长时间http://blahti.wordpress.com/2012/03/03/improved-drag-drop-for-gridview/ 之前有4篇相关的博客文章在那里更详细地解释了什么。

答案 6 :(得分:0)

您可能需要PagedDragDropGrid项目:https://github.com/mrKlar/PagedDragDropGrid

它提供自定义ViewGroup(类似于GridView),具有平滑重新排序功能(与您的视频完全相同)。可能它需要一些自定义,但它是值得的。

希望它会有所帮助。

答案 7 :(得分:0)

这是来自h6ah4i的library,利用Recycler Views提供具有重新排序功能的拖放网格视图。

答案 8 :(得分:0)

Google最近几个月前发布了一些代码实验室。 https://codelabs.developers.google.com/codelabs/android-training-adaptive-layouts/index.html?index=..%2F..%2Fandroid-training#0

您可以在此处查看解决方案 https://github.com/google-developer-training/android-fundamentals-apps-v2/tree/master/MaterialMe-Resource

它们使用可移动卡进行网格布局,可以使用itemTouchHandler将可移动卡拖放到布局中的任何位置。

有关如何执行拖放操作的更详细的代码是here 您需要查看 任务3:使CardView可滑动,可移动和可点击 部分