android 具有多个可选片段的Jetpack合成导航

hzbexzde  于 2023-01-07  发布在  Android
关注(0)|答案(2)|浏览(145)

https://developer.android.com/jetpack/compose/navigation#optional-args
我一直在查阅文档,以了解如何使用多个可选参数以及如何传递它们
但是在文档中只提到一个参数。

composable(
    "profile?userId={userId}",
    arguments = listOf(navArgument("userId") { defaultValue = "me" })
)

然后用

composable("profile")
composable("profile/user123") // if you want to pass param

如何声明和调用两个参数?

68bkxrlz

68bkxrlz1#

如何申报?

composable(
    "profile?userId={userId}&userType={userType}",
    arguments = listOf(
      navArgument("userType") {
        defaultValue = "ADMIN"
        type = NavType.StringType
      }, navArgument("userId") {
        nullable = true
        defaultValue = null
        type = NavType.StringType
      })
  )

怎么打电话?

navController.navigate("profile?userId=user123&userType=user")
navController.navigate("profile?userType=user")
navController.navigate("profile")
mlmc2os5

mlmc2os52#

下面是使用多个可选参数的详细答案

// Syntax to declare 
NavHost(...) {
    composable(
        "profile?userId={userId}&username={username}&address={address}",
        arguments = listOf(
            navArgument("userId") { 
                type = NavType.IntType  
                defaultValue = 86 
            } 
            navArgument("username") { 
                type = NavType.StringType  
                defaultValue = "rahul2211" 
            } 
            navArgument("address") { 
                type = NavType.StringType  
                defaultValue = "India" 
            } 
        ) 
    ) { backStackEntry -> 
        val userId = backStackEntry.arguments?.getInt("userId") 
        val username = backStackEntry.arguments?.getInt("username") 
        val address = backStackEntry.arguments?.getInt("address") 
        Profile(navController, userId, username, address) 
    } 
}

这就是您如何选择性地将参数传递给Profile()组合函数

// Syntax to call 

navController.navigate("profile?userId=102&username=shrekssid&address=Germany")     
// userId = 102, username = "shrekssid", address = "Germany"

navController.navigate("profile?address=Italy")                                     
// userId = 86, username = "rahul2211", address = "Italy"

navController.navigate("profile?userId=991&address=Germany")                        
// userId = 991, username = "rahul2211", address = "Germany"

navController.navigate("profile")                                                   
// userId = 86, username = "rahul2211", address = "India"

相关问题