Store new position of RecyclerView items in SQLite after being dragged and dropped

后端 未结 1 1057
盖世英雄少女心
盖世英雄少女心 2020-12-29 00:57

I have a two dimensional ArrayList of type String which is the input to the adapter class of the RecyclerView. The data in the list is

相关标签:
1条回答
  • 2020-12-29 01:16

    You need a field in each DB row for storing the order. Then you need to implements those features:

    • On new row insert (when you insert a new object in database) you need to set the order field to the next int. You can get the current max value (with sql function MAX) and then simply do +1

    • When user move an item in RecyclerView, in method onMovedyou must update all other rows. You can use the fromPos and toPos for that. More on that below

    • When you fill your RecyclerView with data you need to order them by order field



    Explanation of 2nd feature to be implemented: basically you need to update all rows with order between fromPos and toPos:

    • if user moved the item up (for example from position 4 to 2), you need to:

      1. get primary key field of current item (using position 4)
      2. change all rows between order 2 and order 4: so change 2 -> 3 and 3 -> 4
      3. Change current item order (using primary key of first point) to toPos: in this example change current item order to 2
    • if user moved the item down (for example from position 2 to 4) you need to:

      1. get primary key field of current item (using position 2)
      2. change all rows between order 2 and order 4: so change 4 -> 3 and 3 -> 2
      3. change current item order (using primary key of first point) to toPos: in this example change current item order to 4


    Hope it helps a little

    0 讨论(0)
提交回复
热议问题