Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Reordering of ListView items is quite easy on iOS. Now I would like to do the same thing on Android but it seems to be quite cumbersome: Item reorder is not supported by the SDK and one has to implement it on its own or use use a third-party implementation.

I found several articles and posts dealing with this question but they were all quite old (2-3 years). For example the bauerca DragSortListView is referenced on many places, but the project is no longer maintained. Since my app should support Android 4+ only I wanted to ask if meanwhile there is a better to do this.

Of course drag 'n drop reorder would be the most convenient way for the user but I am open for any solution that works (e.g. using a context menu with up/down)

What is the best way to provide item reorder in Android 4+?

Is there something like a default/standard way of doing this?

like image 618
Andrei Herford Avatar asked Jun 17 '14 07:06

Andrei Herford


1 Answers

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);
like image 155
113408 Avatar answered Oct 24 '22 10:10

113408