kotlin Jetpack与材料3合成:NavigationDrawer -将路径添加到NavigationDrawerItem

ux6nzvsh  于 2023-08-06  发布在  Kotlin
关注(0)|答案(1)|浏览(121)

我正在学习Jetpack与材料合成3.我的Testapplication现在有一个ModalNavigationDrawer,工作正常。但问题是,每次当我在HomeScreen上单击HomeScreen的图标时,HomeScreen的另一个示例就会添加到backstack中。我尝试使用ModalDrawerSheetNavigationDrawerItem。我知道我需要向NavigationDrawer添加一个状态变量,它将HomeRoute作为默认值保存,然后在用户单击其中一个NavDrawer图标时覆盖此变量。但是我找不到一种方法来给予NavigationDrawerItem信息,它属于某个路线。有没有可能只用这些组件就能完成所有的事情?或者我必须自己从dataClass中创建Items并将它们传递给Drawersheet?
下面是代码的一部分:

@Composable
     fun MainCompose() {
     val navController = rememberNavController()
     val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
     val items = listOf(Icons.Default.Favorite, Icons.Default.Face, Icons.Default.Email)
     val scope = rememberCoroutineScope()

     ***val currentScreen by remember(mutableStateOf("home")***

     ModalNavigationDrawer(
            drawerState = drawerState, gesturesEnabled = false,
            drawerContent = {

                ModalDrawerSheet(modifier = Modifier.fillMaxWidth(0.8f)) {
                        Spacer(modifier = Modifier.height(12.dp))

                        NavigationDrawerItem(icon = { Icon(items[0], contentDescription = null) },
                            label = { Text(text = "Home") },
                            selected = false,
                            onClick = {
                                        scope.launch { drawerState.close() }
                                        navController.navigate("home"){
                                            popUpTo("home")
                                        }})

字符串
我想告诉NavigationDrawerItem,如果currentScreen与图标的路径具有相同的值,则应忽略单击。我希望我能表达出问题所在。- 谢谢你-谢谢

5sxhfpxr

5sxhfpxr1#

您可以使用LazyColumn,然后使用items方法基于Model类的List创建所有NavigationDrawerItem
使用每个项目的信息创建模型类:

data class NavigationItemModel(
    val route: String,
    val icon: ImageVector,
    val label: @Composable () -> Unit,
)

字符串
使用模型类创建NavigationDrawerItem

val navItems = listOf(
    NavigationItemModel("home", { Text("home") }, Icons.Default.Home),
    // insert other routes
)

val currentRoute by remember { mutableStateOf("home") }

...

LazyColumn {
    items(navItems) { model ->
        NavigationDrawerItem(
            icon = { Icon(model.icon, contentDescription = null) },
            label = model.label,
            selected = (currentRoute == model.route),
            onClick = {
                // Check if already on this route
                if (currentRoute == model.route) {
                    return
                }
                scope.launch { drawerState.close() }
                navController.navigate("home"){
                    popUpTo("home")
                }
                // Update current route
                currentRoute = model.route
            }
        )
    }
}

相关问题