问题
I've implemented a recyclerView with a drag and drop feature in my app. Everything works fine until the app is relaunched --any drag and drop changes were not saved/remembered by the app.
I've tried:
- Using SharedPreference + GSON
- Reading other SQLite answers here on SO like this one: Store new position of RecyclerView items in SQLite after being dragged and dropped
- Reading Paul Burke's Medium Post
My current code looks like this:
In onCreate
ItemViewModel itemViewModel = ViewModelProviders.of(this).get(ItemViewModel.class);
itemViewModel.getAllItems().observe(this, new Observer<List<Item>>() {
@Override
public void onChanged(List<Item> items) {
adapter.setItemList(items);
itemList = items; //Global variable itemList
}
});
The method called when item is dragged/moved
private void swap(int firstPosition, int secondPosition) {
Collections.swap(itemList, firstPosition, secondPosition);
for(int i = 0; i < itemList.size(); i++) {
Item currentItem = itemList.get(i);
ItemViewModel.update(currentItem );
}
adapter.notifyItemMoved(firstPosition, secondPosition);
}
Any ideas how I can let my app save the reordered recyclerView after drag and drop? Thanks in advance.
回答1:
If you wish to preserve the order of your items once you close your app or move to another activity, you will need to add a property to your entity files which will server as an order value for it. Once added, you could access your dao and run an UPDATE
SQL in the Collections.swap
method when reordering items and than on every load of the list, return the items ordered by that property.
来源:https://stackoverflow.com/questions/53297253/save-new-positions-in-room-after-recyclerview-drag-drop