Best way to reorder items in Android 4+ ListView [closed]

This question is quite old however it comes first when you search for “Best way to reorder list items in Android” and it remained without an answer.

The OP asked for ListView as at the time of the question they were the most commonly used. Today, it is better to use the RecyclerView as it offers many advantages over the ListView. One of these advantages is what we need to implement the reordering, ie. ItemTouchHelper.

To see how the RecyclerView is implemented you can have a look at this example :
https://github.com/googlesamples/android-RecyclerView

The part to implement the reordering is to attach to the RecyclerView as follow:

mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);

ItemTouchHelper touchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {

                Collections.swap(dataList, viewHolder.getAdapterPosition(), target.getAdapterPosition());
                mAdapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
                return true;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                // no-op
            }

            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                return makeFlag(ItemTouchHelper.ACTION_STATE_DRAG,
                        ItemTouchHelper.DOWN | ItemTouchHelper.UP | ItemTouchHelper.START | ItemTouchHelper.END);
            }
});
touchHelper.attachToRecyclerView(mRecyclerView);

Leave a Comment