-
Notifications
You must be signed in to change notification settings - Fork 6
Open
Description
Android-DragReorderSample/app/src/main/java/com/yfujiki/android_dragreordersample/MainActivity.kt
Lines 87 to 95 in 2fbfa4f
| fun moveItem(from: Int, to: Int) { | |
| val fromEmoji = emojis[from] | |
| emojis.removeAt(from) | |
| if (to < from) { | |
| emojis.add(to, fromEmoji) | |
| } else { | |
| emojis.add(to - 1, fromEmoji) | |
| } | |
| } |
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;
}
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels