August 18, 2019

ReOrder the list items by drag and drop in xamarin android using RecyclerView

Brief:  Explanation with simple steps to how to re-order the list items by long press, drag and drop using recycler view in xamarin android.
  



In my previous post explained How to create image gallery control in xamarin form, How to encrypt sqlite database.

DescriptionIf you are looking for a requirement of re arranging the list items based on some priority then you are in the right place and here you can go through the example. Lets get in to the steps,

Step1: Create the new xamarin native project and add the below required packages.


Xamarin.Android.Support.v4
Xamarin.Android.Support.v7
On installation of above packages it will install all the required child packages also.

Step2: Create UI
Add new layout file one for recycler view and another one to dispay custom row item. 


ReOrderLayout.axml
In my example considered displaying quiz question with answer requiring to set the item in correct order.

CustomListItemReorder.axml

Step3: Add Interfaces
Need to add two interface to deifne touch and drag
1. IOnStartDragListener.cs   
 OnStartDrag : Called when a view is requesting a start of a drag and accepts viewHolder of the recycler view to drag.

2. ITemTouchHelperAdapter.cs 
OnItemMove : Called when an item has been dragged far enough to trigger a move. This is called every time an item is shifted, and not at the end of a "drop" event. 
OnItemDismiss:Called when an item has been dismissed by a swipe

Step4: Add ItemTouchHelperCallback Class Create new class SimpleItemTouchHelperCallback by inheriting from ItemTouchHelper.Callback

Here overriden below three methods provided by the ItemTouchHelper.Callback base class
1.GetMovementFlags : To update the touch movement state 
2.OnMove : To Notify the adapter of the moved position
3.OnSwiped  : To Notify the adapter of the dismissal


SimpleItemTouchHelperCallback.cs
Step5: Create Adapter and view holder Class
Here ReOrderAdapters implemented ITemTouchHelperAdapter for the above mentioned functionality and IOnLongClickListener
to listen to the long click event.

SimpleItemTouchHelperCallback.cs

Step6:  Add Activity Class
Created the activity ReOrderActivity and implemeted interface IOnStartDragListener.

ReOrderActivity.cs
Git link: https://github.com/suchithm/NativeCodeLog

Screen recording:

This is all about the implementation of reorder list in xamarin android using recycler view. Keep visiting for more exciting stuffs and follow us on FB Page.

No comments:

Post a Comment