从itemtoucjhelper中删除最后一个位置时,第一个位置将被删除

dy1byipe  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(373)

下午好!哪天我绞尽脑汁,我不明白为什么会这样:(当你用刷子删除最后一个位置时,第一个位置被删除,这只发生在最后一个位置。

private NotesAdapter notesAdapter;
private AlertDialog dialogURL;
private static ArrayList<Note> notesFromDB;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(v -> {
        if (!isClick) {
            DetailNoteActivity.start(MainActivity.this, null);
            isClick = true;
        }
    });

    RecyclerView recyclerViewNotes = findViewById(R.id.rv_notes);
    recyclerViewNotes.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));

    notesFromDB = new ArrayList<>();
    notesAdapter = new NotesAdapter();

    MainViewModel viewModel = new ViewModelProvider(this).get(MainViewModel.class);
    viewModel.getNotes().observe(this, notes -> {
        notesFromDB = (ArrayList<Note>) notes;
        notesAdapter.setItems(notesFromDB);
    });

...

private final ItemTouchHelper.SimpleCallback simpleCallback =
        new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView,
                                  @NonNull RecyclerView.ViewHolder viewHolder,
                                  @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                int position = viewHolder.getAdapterPosition();
                App.getInstance().getNoteDao().deleteNote(notesFromDB.get(position));
                notesAdapter.notifyItemRemoved(position);

            }
        };

适配器

public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.NoteViewHolder> {

private final SortedList<Note> sortedList;

public NotesAdapter() {
    sortedList = new SortedList<>(Note.class, new SortedList.Callback<Note>() {
        @Override
        public int compare(Note o1, Note o2) {
            if (!o2.isDone() && o1.isDone()) {
                return 1;
            }
            if (o2.isDone() && !o1.isDone()) {
                return -1;
            }
            return (int) (o2.timestamp - o1.timestamp);
        }

...
任何帮助都将不胜感激。

fcg9iug3

fcg9iug31#

添加到适配器:

public Note getNoteAt(int position){
return sortedList.get(position);

} ...
刷卡时:

@Override
    public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
        App.getInstance().getNoteDao().deleteNote(notesAdapter.getNoteAt(viewHolder.getAdapterPosition()));

    } ...

相关问题