How can I finish the ActionMode when no selected item?

225 Views Asked by At

I want to finish actionmode when there is no item selected. I tried the code below but it didn't work.

    bookAdapter.setOnLongClickListener(new RecyclerViewAdapter.OnLongClickListener() {

        @Override
        public void onLongClick() {

            if(mActionMode != null) {
                if(bookAdapter.getSelectedBooks().isEmpty()) {
                    mActionMode.finish();
                }
                return;
            }

            ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {

                @Override
                public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                    mode.getMenuInflater().inflate(R.menu.delete_book_menu, menu);
                    buttonAddBook.setVisibility(View.INVISIBLE);
                    return true;
                }

                @Override
                public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                    return false;
                }

                @Override
                public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                    switch (item.getItemId()) {
                        case R.id.delete_book :
                            for(Book book : bookAdapter.getSelectedBooks()) {
                                bookViewModel.delete(book);
                            }
                            mode.finish();
                            return true;
                    default:
                        return false;
                    }
                }

                @Override
                public void onDestroyActionMode(ActionMode mode) {
                    mActionMode = null;
                    for(Book book : bookAdapter.getBookList()) {
                        book.setSelected(false);
                        bookAdapter.notifyDataSetChanged();
                    }
                    buttonAddBook.setVisibility(View.VISIBLE);
                }
            };
            mActionMode = startSupportActionMode(mActionModeCallback);
        }
    });

But when I change the code, for example when I try to finish the mode when 2 items are selected, it works. As follows:

            if(mActionMode != null) {
                if(bookAdapter.getSelectedBooks().size() == 2) {
                    mActionMode.finish();
                }
                return;
            }

What am I doing wrong? I will be grateful if you could help me. Thanks in advance.

1

There are 1 best solutions below

0
On

Did you use the recyclerview-selection?

I think this article would be useful. https://proandroiddev.com/a-guide-to-recyclerview-selection-3ed9f2381504