You are on page 1of 2

Navegación compose

Pantalla 1 Pantalla 2

@Composable @Composable
fun Pantalla1(navegarPantalla2: (String) -> Unit) { fun Pantalla2(text: String) {
var textValue by remember {
mutableStateOf("") }
Column(
Column( modifier = Modifier
modifier = Modifier .fillMaxSize()
.fillMaxSize() .padding(16.dp),
.padding(16.dp), verticalArrangement =
verticalArrangement = Arrangement.SpaceAround,
Arrangement.SpaceAround, horizontalAlignment =
horizontalAlignment = Alignment.CenterHorizontally
Alignment.CenterHorizontally ){
){ Text(
Text( text = text,
text = "PANTALLA 1", style = TextStyle(color = Color.Black,
style = TextStyle(color = Color.Black, fontSize = 42.sp, fontWeight = FontWeight.Black)
fontSize = 42.sp, fontWeight = FontWeight.Black) )
) }
TextField(value = textValue, onValueChange }
= { textValue = it },

label = {
Text(
text = "Introducir texto"
)

})
Button(onClick = {
navegarPantalla2(textValue) }) {
Text(text = "Enviar")
}
}
}
sealed class Destinations(
var route: String
){
object Pantalla1 : Destinations("pantalla1")
//Si queremos que sea null ?
object Pantalla2 : Destinations("pantalla2/?newText={newText}") {
fun createRoute(newText: String) = "pantalla2/?newText=$newText"
}
}
@Composable
fun NavigationHost() {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = Destinations.Pantalla1.route) {
composable(Destinations.Pantalla1.route) {
Pantalla1(
navegarPantalla2 = { newText ->
navController.navigate(Destinations.Pantalla2.createRoute(newText = newText))
}
)
}
composable(
Destinations.Pantalla2.route,
arguments = listOf(navArgument("newText") { defaultValue = "Pantalla 2" })
) { navBackStackEntry ->
val newText = navBackStackEntry.arguments?.getString("newText")
requireNotNull(newText)
Pantalla2(newText)
}
}
}
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
EjemploBasicoDeNavegacionComposeTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
NavigationHost()
}
}
}
}
}

You might also like