Marat
Marat

Reputation: 6703

How to implement Drag&Drop in listview?

I have found that most of the similar questions were asked years ago. Therefore, I would like to know if there are a new and easier ways to implement drag&drop functionality to listview? I'm taking the data from sqilte db for my listview object. I didn't find some straightforward tutorial. If there is please share the link.

I found this video: https://www.youtube.com/watch?v=_BZIvjMgH-Q but the link for code is not working.

Upvotes: 2

Views: 568

Answers (1)

Marat
Marat

Reputation: 6703

As it was told in the comments the easiest way to implement Drag&Drop by using RecyclerView. It includes the special class named ItemTouchHelper which can easy handle the drag&drop feature. In case of ListView you will need to write a lot more code compared to RecyclerView.

The following code is what I have found useful:

ItemTouchHelper item = new ItemTouchHelper(new ItemTouchHelper.Callback() {

        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            int swipeFlags = 0;
            return makeMovementFlags(dragFlags, swipeFlags);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            Collections.swap(dateList, viewHolder.getAdapterPosition(), target.getAdapterPosition());
            adapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
            return true;
        }

        @Override
        public void onMoved(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, int fromPos, RecyclerView.ViewHolder target, int toPos, int x, int y) {
            super.onMoved(recyclerView, viewHolder, fromPos, target, toPos, x, y);
            Toast.makeText(MainActivity.this, "Moved", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {}
    });

    item.attachToRecyclerView(recyclerView);

Upvotes: 1

Related Questions