Android compose navigation带参数跳转

object ParamsConfig {
    const val PARAMS_NAME = "name"
    const val PARAMS_AGE = "age"
}
object RouteConfig {
    const val ROUTE_PAGEONE="pageOne"
    const val ROUTE_PAGETWO="pageTwo"
}
@Composable
fun NavHostDemo() {
    val navController = rememberNavController()
    NavHost(navController = navController, startDestination = RouteConfig.ROUTE_PAGEONE) {
        composable(RouteConfig.ROUTE_PAGEONE) {
            PageOne(navController)
        }
        composable(
            "${RouteConfig.ROUTE_PAGETWO}/{${ParamsConfig.PARAMS_NAME}}/{${ParamsConfig.PARAMS_AGE}}",
            arguments = listOf(
                navArgument(ParamsConfig.PARAMS_NAME) {type = NavType.StringType},
                navArgument(ParamsConfig.PARAMS_AGE) {
                    type = NavType.IntType })

        ) {
            val argument = requireNotNull(it.arguments)
            val name = argument.getString(ParamsConfig.PARAMS_NAME)
            val age = argument.getInt(ParamsConfig.PARAMS_AGE)
            PageTwo(name, age, navController)
        }
    }
}

@Composable
fun PageOne(navController: NavController) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight()
            .background(Color.White)
    ) {
        Text(text = "这是页面1")
        Spacer(modifier = Modifier.height(20.dp))
        Button(onClick = {
            //点击跳转到页面2
            navController.navigate("${RouteConfig.ROUTE_PAGETWO}/黄林晴/20")
        }, colors = ButtonDefaults.buttonColors(containerColor = Color.Red)) {
            Text(
                text = "跳转页面2",
                modifier = Modifier.fillMaxWidth(),
                textAlign = TextAlign.Center
            )
        }
    }
}
@Composable
fun PageTwo(name:String?,age: Int,navController: NavController) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight()
            .background(
                Color.White
            )
    ) {
        Text(text = "我是${name} 今年${age}岁")
        Spacer(modifier = Modifier.height(20.dp))
        Button(onClick = {
            //点击返回页面1
            navController.popBackStack()
        }, colors = ButtonDefaults.buttonColors(containerColor = Color.Blue)) {
            Text(
                text = "返回页面1",
                modifier = Modifier.fillMaxWidth(),
                textAlign = TextAlign.Center
            )
        }
    }
}

implementation "androidx.constraintlayout:constraintlayout-compose:1.0.1"
implementation("androidx.navigation:navigation-compose:2.5.3")

你可能感兴趣的:(android,前端,javascript)