Austin Mauldin Austin Mauldin - 1 year ago 77
Java Question

use editText to reorder an ArrayList

I'm using an ArrayList to populate a RecyclerView, and I have attached Buttons that point up and down to each element of the RecycledView. I would like to set an

to my
button which intends move that respective elements position up or down in the ArrayList. This will occur in my RecyclerView's Adapter class inside the following method:

onBindViewHolder(final ViewHolder holder, final int position) {
//updateBtn is declared and initialized in the ViewHolder
holder.upBtn.setOnClickListener(new View.OnClickListener(){
//arrayList.set(newPosition, object?);

In this case I know I should subtract 1 from the current position in order to make that element move up in the list and add 1 for that element to move down. BUT I feel like I'm missing some logic here and I'm really not sure what do. How could I make to above code re-order my list in that particular case move the element up e.g. from position 1 in the array to position 0

Answer Source

Use Collections.swap method:

Collections.swap(arrayList, position, newPosition);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download