Josef M
Josef M

Reputation: 406

Navigating between composable's using a Navigation Drawer in Jetpack Compose

I am trying to set up navigation for the drawer icons/textfield in jetpack compose but not exactly sure how to do it properly. How can I set the navigation so that whenever I click in one of the Icons I get navigated to that composable screen? This is currently my MainDrawer layout:


@Composable
fun MainDrawer() {

    val scaffoldState = rememberScaffoldState()
    val scope = rememberCoroutineScope()
    Scaffold(
        scaffoldState = scaffoldState,
        topBar = {
            AppBar(
                onNavigationIconClick = {
                    scope.launch {
                        scaffoldState.drawerState.isOpen
                    }
                }
            )
        },
        drawerContent = {
            DrawerHeader()
            DrawerBody(
                items = listOf(
                    MenuItem(

                        id = "item1",
                        title = "item1",
                        contentDescription = "Go to item1 screen",
                        icon = Icons.Default.Home
                    ),
                    MenuItem(
                        id = "item2",
                        title = "item2",
                        contentDescription = "Go to item2 screen",
                        icon = Icons.Default.Settings
                    ),
                    MenuItem(
                        id = "item3",
                        title = "item3",
                        contentDescription = "Ge to item3",
                        icon = Icons.Default.Info
                    ),
                    MenuItem(
                        id = "item4",
                        title = "item4",
                        contentDescription = "Go to Your item4",
                        icon = Icons.Default.Info
                    ),
                    MenuItem(
                        id = "item5",
                        title = "item5",
                        contentDescription = "Your item5",
                        icon = Icons.Default.Info
                    ),
                    MenuItem(
                        id = "item6",
                        title = "item6",
                        contentDescription = "Your item6",
                        icon = Icons.Default.Info
                    ),
                    MenuItem(
                        id = "item7",
                        title = "item7",
                        contentDescription = "item7",
                        icon = Icons.Default.Info
                    ),
                    MenuItem(
                        id = "item8",
                        title = "item8",
                        contentDescription = "item8",
                        icon = Icons.Default.Info
                    ),
                )
            ) {
                println("Clicked on ${it.title}")
            }
        }
    ) {

    }
}

Drawer Body: This contains the element of the body

@Composable
fun DrawerBody(
    items: List<MenuItem>,
    modifier: Modifier = Modifier,
    itemTextStyle: TextStyle = TextStyle(fontSize = 18.sp),
    onItemClick: (MenuItem) -> Unit
) {
    LazyColumn(modifier) {
        items(items) { item ->
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable {
                        onItemClick(item)
                    }
                    .padding(16.dp)
            ) {
                Icon(
                    imageVector = item.icon,
                    contentDescription = item.contentDescription
                )
                Spacer(modifier = Modifier.width(16.dp))
                Text(
                    text = item.title,
                    style = itemTextStyle,
                    modifier = Modifier.weight(1f)
                )
            }
        }

    }

}

Upvotes: 3

Views: 3692

Answers (1)

Josef M
Josef M

Reputation: 406

I managed to solve this issue. This is how it will work: https://gyazo.com/4c32e855becff72f8979650545ad7f39

This is how I did it:

  1. Begin by adding the dependencies to your project:
 // Navigation with Compose
    implementation "androidx.navigation:navigation-compose:2.5.0"

    // Modal Drawer Layout
    implementation "androidx.drawerlayout:drawerlayout:1.1.1"

 // Coroutines
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4"

  1. Start by creating the TopAppBar for the app. This is the following code:

@Composable
fun TopBar(scope: CoroutineScope, scaffoldState: ScaffoldState) {
    TopAppBar(
        title = { Text(text = stringResource(R.string.app_name), fontSize = 18.sp) },
        navigationIcon = {
            IconButton(onClick = {
                scope.launch {
                    scaffoldState.drawerState.open()
                }
            }) {
                Icon(Icons.Filled.Menu, "")
            }
        },
        backgroundColor = colorResource(id = R.color.purple_200),
        contentColor = Color.White
    )
}
  1. Next, create a sealed class. This class will represent the items you want inside your drawer. I put the following as an example:
sealed class NavDrawerItem(var route: String, var icon: Int, var title: String) {
    object Add : NavDrawerItem("add", android.R.drawable.ic_menu_add, "Add")
    object Edit : NavDrawerItem("edit", android.R.drawable.ic_menu_edit, "Edit")
    object Search : NavDrawerItem("search", android.R.drawable.ic_menu_search, "Search")
    object Location : NavDrawerItem("location", android.R.drawable.ic_menu_mylocation, "Location")
    object Preferences : NavDrawerItem("preferences", android.R.drawable.ic_menu_preferences, "Preferences")
}
  1. Now, create the highlighter. When an item in the drawer has been pressed, this will highlight what item has been pressed.
@Composable
fun DrawerItem(item: NavDrawerItem, selected: Boolean, onItemClick: (NavDrawerItem) -> Unit) {
    val background = if (selected) R.color.purple_200 else android.R.color.transparent
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = { onItemClick(item) })
            .height(45.dp)
            .background(colorResource(id = background))
            .padding(start = 10.dp)
    ) {
        Image(
            painter = painterResource(id = item.icon),
            contentDescription = item.title,
            colorFilter = ColorFilter.tint(Color.White),
            contentScale = ContentScale.Fit,
            modifier = Modifier
                .height(35.dp)
                .width(35.dp)
        )
        Spacer(modifier = Modifier.width(7.dp))
        Text(
            text = item.title,
            fontSize = 18.sp,
            color = Color.White
        )
    }
}
  1. Here we create each screen for the respective items. 1 composable screen for each item. I created an easy and quick screen but you can do your own screens here.
@Composable
fun AddScreen() {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(colorResource(id = R.color.myColor))
            .wrapContentSize(Alignment.Center)
    ) {
        Text(
            text = "Add Screen",
            fontWeight = FontWeight.Bold,
            color = Color.White,
            modifier = Modifier.align(Alignment.CenterHorizontally),
            textAlign = TextAlign.Center,
            fontSize = 25.sp
        )
    }
}

@Composable
fun EditScreen() {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(colorResource(id = R.color.myOrange))
            .wrapContentSize(Alignment.Center)
    ) {
        Text(
            text = "Edit Screen",
            fontWeight = FontWeight.Bold,
            color = Color.White,
            modifier = Modifier.align(Alignment.CenterHorizontally),
            textAlign = TextAlign.Center,
            fontSize = 25.sp
        )
    }
}

@Composable
fun SearchScreen() {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(colorResource(id = R.color.purple_500))
            .wrapContentSize(Alignment.Center)
    ) {
        Text(
            text = "Search Screen",
            fontWeight = FontWeight.Bold,
            color = Color.White,
            modifier = Modifier.align(Alignment.CenterHorizontally),
            textAlign = TextAlign.Center,
            fontSize = 25.sp
        )
    }
}

@Composable
fun LocationScreen() {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(colorResource(id = R.color.myGreen))
            .wrapContentSize(Alignment.Center)
    ) {
        Text(
            text = "Location Screen",
            fontWeight = FontWeight.Bold,
            color = Color.White,
            modifier = Modifier.align(Alignment.CenterHorizontally),
            textAlign = TextAlign.Center,
            fontSize = 25.sp
        )
    }
}

@Composable
fun PreferencesScreen() {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(colorResource(id = R.color.myGreen))
            .wrapContentSize(Alignment.Center)
    ) {
        Text(
            text = "Preference Screen",
            fontWeight = FontWeight.Bold,
            color = Color.White,
            modifier = Modifier.align(Alignment.CenterHorizontally),
            textAlign = TextAlign.Center,
            fontSize = 25.sp
        )
    }
}
  1. Now we need to create the actual navigation using a navcontroller and navHostController. We do this in the following way:
@Composable
fun ComposeNavigation(navController: NavHostController) {
    NavHost(navController, startDestination = NavDrawerItem.Add.route) {
        composable(NavDrawerItem.Add.route) {
            AddScreen()
        }
        composable(NavDrawerItem.Edit.route) {
            EditScreen()
        }
        composable(NavDrawerItem.Search.route) {
            SearchScreen()
        }
        composable(NavDrawerItem.Location.route) {
            LocationScreen()
        }
        composable(NavDrawerItem.Preferences.route) {
            PreferencesScreen()
        }
    }
}

  1. After, create DrawerLayout with all the items, coroutines and navbackstack.
@Composable
fun DrawerLayout(scope: CoroutineScope, scaffoldState: ScaffoldState, navController: NavController) {
    val items = listOf(
        NavDrawerItem.Add,
        NavDrawerItem.Edit,
        NavDrawerItem.Search,
        NavDrawerItem.Location,
        NavDrawerItem.Preferences
    )
    Column {
// Header
        Image(
            painter = painterResource(id = R.drawable.ic_launcher_foreground),
            contentDescription = R.drawable.ic_launcher_foreground.toString(),
            modifier = Modifier
                .height(100.dp)
                .fillMaxWidth()
                .padding(10.dp)
        )
        Spacer(
            modifier = Modifier
                .fillMaxWidth()
                .height(5.dp)
        )
        val navBackStackEntry by navController.currentBackStackEntryAsState()
        val currentRoute = navBackStackEntry?.destination?.route
        items.forEach { item ->
            DrawerItem(item = item, selected = currentRoute == item.route, onItemClick = {
                navController.navigate(item.route) {
                    navController.graph.startDestinationRoute?.let { route ->
                        popUpTo(route) {
                            saveState = true
                        }
                    }
                    launchSingleTop = true
                    restoreState = true
                }
                scope.launch {
                    scaffoldState.drawerState.close()
                }
            })
        }
    }
}

  1. Finally we create the mainLayout that will work as the main frame for our app. Here will use a scaffold for the topbar and drawercontent:
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun MainLayout() {

    val scaffoldState = rememberScaffoldState(rememberDrawerState(DrawerValue.Closed))
    val scope = rememberCoroutineScope()
    val navController = rememberNavController()

    Scaffold(
        scaffoldState = scaffoldState,
        topBar = { TopBar(scope = scope, scaffoldState = scaffoldState) },
        drawerBackgroundColor = colorResource(id = R.color.myColor),
        drawerContent = {
            DrawerLayout(scope = scope, scaffoldState = scaffoldState, navController = navController)
        },
    ) {

        ComposeNavigation(navController = navController)
    }
}

Hope this helped anyone looking for a functional navigation drawer! Feel free to give it a arrowUp if this works for you. Happy Coding!

Upvotes: 7

Related Questions