Android-DragReorderSample
Android-DragReorderSample copied to clipboard
moveItem doesn't reorder items properly
https://github.com/yfujiki/Android-DragReorderSample/blob/2fbfa4f425917e544ed580231be2370b6d1767da/app/src/main/java/com/yfujiki/android_dragreordersample/MainActivity.kt#L87-L95
Imagine you move items from 0 position to 1
- First your remove items at 0 position
- Then you add item again to 0 position such as to > from and you add to to-1 position
The proper solution may be like this:
fun moveItem(from: Int, to: Int) {
val fromEmoji = emojis[from]
emojis.removeAt(from)
emojis.add(to, fromEmoji)
}
Test
@Test
public void testMoveItem() {
List<Integer> list = Arrays.asList(0, 1, 2, 3, 4, 5);
assertEquals(
Arrays.asList(1, 0, 2, 3, 4, 5),
moveItem(list, 0, 1));
assertEquals(
Arrays.asList(1, 2, 0, 3, 4, 5),
moveItem(list, 0, 2));
assertEquals(
Arrays.asList(1, 2, 3, 4, 5, 0),
moveItem(list, 0, 5));
assertEquals(
Arrays.asList(0, 1, 2, 3, 5, 4),
moveItem(list, 5, 4));
assertEquals(
Arrays.asList(5, 0, 1, 2, 3, 4),
moveItem(list, 5, 0));
assertEquals(
Arrays.asList(0, 1, 2, 4, 3, 5),
moveItem(list, 3, 4));
assertEquals(
Arrays.asList(0, 1, 2, 4, 3, 5),
moveItem(list, 4, 3));
}
public <T> List<T> moveItem(List<T> data, int from, int to) {
data = new ArrayList<>(data);
T item = data.get(from);
data.remove(from);
data.add(to, item);
return data;
}
Looks like solution needs correction for penultimate item movement
Looks like solution needs correction for penultimate item movement
Ah, no, that is my project code only specific issue
I agree with @httpdispatch I used this logic and it doesn't work for the first item as mentioned by @httpdispatch
The correct solution should be
fun moveItem(from: Int, to: Int) {
val fromEmoji = emojis[from]
emojis.removeAt(from)
emojis.add(to, fromEmoji)
}