I'm building an application that will allow users to pick from a RecyclerView list, highlighting their choice. The problem is that in order to highlight an item for the first time, a long press is needed. (Afterwards, a short click is enough to do the selection.)
I haven't found anything in the documentation to indicate why this happens.
I'm using SelectionTracker
Specifically following this guide
Here's the code : https://github.com/marcosholgado/multiselection
Expectations: I expect the item on the RecyclerView to be selected every time someone short clicks on it.
Reality: In order to select an item for the first time, the user needs to long press it.
Any Ideas?
Just override SelectionHotspot to return true. That's all you need
fun getItemDetails(): ItemDetailsLookup.ItemDetails<Long> =
object : ItemDetailsLookup.ItemDetails<Long>() {
override fun getPosition(): Int = adapterPosition
override fun getSelectionKey(): Long? = itemId
override fun inSelectionHotspot(e: MotionEvent): Boolean { return true }
}
While I couldn't think of a solution that doesn't involve reimplementing both a MotionInputHandler
and a SelectionTracker.Builder
(as mentioned in the guide), there is a neat trick to achieve the behaviour you want.
We know that the TouchInputHandler
selects items on single click as long as the SelectionTracker
is not empty. That means if we have some special key saved in the SelectoinTracker
that's not associated with a real list item we practically 'activate' the on single click selection mode this way. However we also have to make sure that our KeyProvider
doesn't provide that same special key to keep our data consistent.
So assuming you have picked a special key, say ghostKey
, activating and deactivating the selection mode is now a matter of calling mSelectionTracker.select(ghostkey)
or mSelectionTracker.clearSelection()
. You can then execute these calls however you like, be that having a button that activates and deactivates the selection mode or simply calling that during the hosting view creation process i.e onCreate
, onCreateView
etc..
If you are using Kotlin you can also define some Extensions that wrap these calls for you, so you'd be able to do things like mSelectionTracker.enable()
or mSelectionTracker.disable()
Use this line
selectionTracker.select(item.getSelectionKey());
On this override method
.withOnItemActivatedListener(new OnItemActivatedListener() {
@Override
public boolean onItemActivated(@NonNull ItemDetailsLookup.ItemDetails item, @NonNull MotionEvent e) {
selectionTracker.select(item.getSelectionKey());
return true;
}
})
I solved like this. Keep coding..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With