bignerdranch / recyclerview-multiselect

DNA - An open-source library that we should likely deprecate. Unarchiving this repo will give us a chance to tie up any loose ends and deprecate it.
http://bignerdranch.github.io/recyclerview-multiselect
MIT License
415 stars 82 forks source link

Leaving selection mode (and action mode) if no item is selected #31

Open Adrianrff opened 7 years ago

Adrianrff commented 7 years ago

Hi, thank you for this library, it makes things much easier.

I want to leave selection mode and turn off the action mode bar if the user clicks the only remaining selected item. I've tried doing it like this

  @Override
  public void onClick(View v) {
     if (!mMultiSelector.tapSelection(TaskListViewHolder.this)){
        mPresenter.showBottomSheet(tasks.get(getAdapterPosition()), getAdapterPosition(), true);
     }

     if (mMultiSelector.getSelectedPositions().isEmpty()){
        mMultiSelector.setSelectable(false);
     }
  }

But it doesn't work. The selection mode is turned off, but the action mode bar is not. What's strange is that if I call that outside the view holder, it does work. I implemented it succesfullt in onBackPressed using simply this:

public void leaveSelectMode(){ mMultiSelector.clearSelections(); mMultiSelector.setSelectable(false); }

but it doesn't work in onClick.

Am i doing something wrong?

Thanks in advance

venturachrisdev commented 7 years ago

@Adrianrff If you're using your activity as a listener for your adapter, in your SwappingViewHolder.onLongClick method you could call something like:

@Override
        public boolean onLongClick(View v) {
            if (!multiSelector.isSelectable()) { // there's no item selected, start the action mode
                listener.onLongClick(); // in my activity (or fragment, I setup the action mode)
                multiSelector.setSelectable(true);
            } // selection mode is activated so I just need to add selected items
            multiSelector.setSelected(NotesViewHolder.this, true);
            listener.onSelectedItem(); // in my activity/fragment, triggered every  time an item is selected

            return true;
        }

Then in my listener implementation

public void onSelectedItem() {
        int selectedCount = mAdapter.multiSelector.getSelectedPositions().size();
        if (selectedCount > 0) {
              // do stuff, there are Items selected (at least one)
        } else {
            // there's no items selected, so leave the action mode
           if (mActionmode != null) {
                mActionmode.finish();
           }
        }
    }

Note: mActionmode is set in the ModalMultiSelectorCallback.onCreateActionMode

Adrianrff commented 7 years ago

Thank you. I figured it out a few moments ago. The problem was that I wasn't manually finishing the action mode. What confuses me though is why it works outside the view holder by calling setSelectable(false) without manually finishing action mode.