Multi-List Item Selection in Jetpack Compose
The option to select multiple items in a list is a very common functionality we can see in a lot of apps like Gmail, WhatsApp, Files, Messages, etc.
We will explore the process of developing a similar user interface (UI) using Jetpack Compose.
Started Code
A LazyColumn
displaying a list of strings using ListItem
.
Steps to add multi-selection support
- Add a state to determine whether the list is in selection mode or not.
- Add a state to store the selected items when the list is in selection mode.
- Using the states, update the UI for
ListItem
andAppBar
. - Add
BackHandler
to intercept back press when in selection mode.
Adding States
We can use a Boolean
state to store if the list is in selection mode or not.
We can use a list to store the keys for the selected items. The key can be Int
, String
or anything applicable.
TopAppBar changes
Add a condition to toggle the TopAppBar
based on selection mode.
Similarly, we can do this for any UI on the screen.
Back Handler
When in selection mode, on back press we can intercept it to clear the selection mode.
Clear the Selection Mode when no item is selected
This is a common behaviour we can observe in most of the apps using a multi-selection mode.
When all the selected items are deselected, the selection mode is automatically reset.
This can be done using LaunchedEffect
like this.
Complete code
Please comment with your valuable feedback.
It would help me to improvise.
Kindly 👏👏👏 if this was useful.
Please follow if you want more content related to Android and Jetpack Compose.
LinkedIn: https://www.linkedin.com/in/abhimanyu-n/