使用Itemtouchhelper更改会议室数据库的顺序

时间:2019-04-09 09:55:50

标签: android android-room

我有一个使用recyclerview来显示数据库项目的应用程序。我想通过使用itemtouchhelper拖动来重新排列项目。我想出了办法,但不知道如何更新房间数据库。

ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT|ItemTouchHelper.DOWN|ItemTouchHelper.UP, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {

            int dragFrom = -1;
            int dragTo = -1;
            boolean listChanged = false;

            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder viewHolder1) {
                int from = viewHolder.getAdapterPosition();
                int to = viewHolder1.getAdapterPosition();

                if(dragFrom == -1) {
                    dragFrom =  from;
                }
                dragTo = to;
                listChanged = true;

                Collections.swap(mGames, from, to);
                gameAdapter.notifyItemMoved(from, to);

                return true;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
                mGames.remove(viewHolder.getAdapterPosition());
                Game game = mGames.get(viewHolder.getAdapterPosition());
                mGameViewModel.deleteGame(game);
                gameAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
            }

            @Override
            public void onSelectedChanged(@Nullable RecyclerView.ViewHolder viewHolder, int actionState) {
                super.onSelectedChanged(viewHolder, actionState);

                if(actionState == ItemTouchHelper.ACTION_STATE_IDLE && listChanged){

                    //update database

                    listChanged = false;
                }
            }
        });

例如,我将项目3拖到位置6,然后项目4变成项目3,5变成4,而6变成5。

是否有一种特殊的方法,或者我必须自己找到一个方法?

0 个答案:

没有答案