Android-DragReorderSample icon indicating copy to clipboard operation
Android-DragReorderSample copied to clipboard

moveItem doesn't reorder items properly

Open httpdispatch opened this issue 5 years ago • 3 comments

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;
    }

httpdispatch avatar May 22 '20 05:05 httpdispatch

Looks like solution needs correction for penultimate item movement

httpdispatch avatar May 22 '20 05:05 httpdispatch

Looks like solution needs correction for penultimate item movement

Ah, no, that is my project code only specific issue

httpdispatch avatar May 22 '20 06:05 httpdispatch

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)    
    }

dudhatparesh avatar Aug 10 '20 16:08 dudhatparesh