Highlight your Selected Drawer Item: Jetpack Compose
In this article, we will be implementing the one missing feature of our Drawer in Compose, and that is to highlight the selected item so that the user will know which Screen you are in.
Output:
Implementation:
This article is an extension of previous article on Creating a Drawer in Compose.
After creating the drawer successfully, now we need to know about the selected item at the beginning of our application. In our case, we have Home screen as the default/entry screen in the app. So, we will create a variable to store the current Selected Drawer item and initialize it with “Home”.
Use remember API to trigger recomposition on Screen changes.
var selectedDrawerItem by rememberSaveable {
mutableStateOf(Screen.Home.title)//Entry Screen is Home
}
Here, we are using rememberSaveable to survive configuration changes too.
Drawer(selectedDrawerItem, ... ) //Pass the selectedItem
{ route ->//This is the Clicked Drawer Item
selectedDrawerItem = route //Change the selectedItem
.....
}
In continuation with the Drawer composable that we created in our previous article…
@Composable
fun Drawer(
selectedDrawerItem: String,
...
) {
LazyColumn(state = drawerLazyListState) {
...
items(screens)
{ item ->
Row(
modifier = Modifier
.background(
if (selectedDrawerItem == item.title) {//if current Drawer item is the selectedItem
Color.DarkGray.copy(0.1f)//Highlight the background
} else {//If current one is not the selectedItem
Color.White
}
)
.padding(vertical = 1.dp)
.fillMaxWidth()
.clickable {
onItemClick(item.title)
}
.padding(16.dp)
) {
//Each row item
}
}
}
}
That’s it, now we will just add a highlighted background color to the selected item in the drawer list.
Our steps are…
- Create selectedDrawerItem variable.
- Adding Drawer in the Scaffold.
- Pass the selectedItem in Drawer compose.
- Change the selectedItem in OnItemClick of Drawer.
- Modify the background color of the selected item.
Now, we are done here. Enjoy your cool feature and give your user a great experience.
I hope you found this helpful. If yes, then do FOLLOW me for more Android-related content.
#androidWithSagar #android #androiddevelopment #development #compose #kotlin