Eike Cochu
Eike Cochu

Reputation: 3435

Recyclerview selection + clickable items

I recently implemented a small RecyclerView setup and tried out the recyclerview-selection library. So far, the selection works fine but I also connected a click handler on the recyclerview items and now every time I long-press an item to activate the selection mode, it also counts as a simple tap and the activity changes (because that is what I programmed it to do on item tap). I managed to avoid this by adding a simple boolean to my recyclerview adapter, which is called when the selection mode starts:

void setIgnoreClicks(boolean b) {
    this.ignoreClicks = b;
}

and then in the bind-function of my viewholder:

void bind(MyModelClass m) {
    ...
    view.setOnClickListener(() -> {
        if(!adapter.isIgnoreClicks()) {
            ...
        }
    });
}

now when the selection mode ends, the boolean is set back to false and the taps go through again.

The problem is that when only one item selected and you tap on it to deselt it, the selection mode is also exited - which is fine, except that that tap is now not ignored anymore and so, the activity changes. What I want basically is to ignore that last tap too. Is there some way to stop the event if the selection mode is still active?

Thanks

Upvotes: 2

Views: 832

Answers (1)

Eike Cochu
Eike Cochu

Reputation: 3435

Ok, solved this myself. What I did was to add a touch listener to my recyclerview which sets the ignoreClick to true if the actionmode is active and no item is clicked:

modelList.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
    @Override
    public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
        if (e.getAction() != MotionEvent.ACTION_UP)
            return false;
        if(actionMode != null)
            ignoreClick = rv.findChildViewUnder(e.getX(), e.getY()) != null; // ignore click if child is null (not clicked on a child, but the empty background of the recycler view)
        return false;
    }

    ...
});

and then in my item click handler:

private void showDetails(final Model model) {
    if(ignoreClick)
        ignoreClick = false; // the click is ignored, reset to false
    else if (!selectionTracker.hasSelection()) {
        final Intent intent = new Intent(MainActivity.this, ModelViewActivity.class);
        intent.putExtra(Codes.DATA_MODEL, model);
        startActivityForResult(intent, Codes.INTENT_MODEL_SHOW);
    }
}

Upvotes: 1

Related Questions