How to select first item without long press using RecyclerView's SelectionTracker
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()