Ejemplo práctico 3: BoxWithConstraints adaptativo

Objetivo

Este ejemplo muestra un texto diferente según si el ancho del contenedor es mayor o menor a 300.dp. Además, el fondo cambia de color para mayor visibilidad.

Composable EjemploBoxWithConstraints

 1@SuppressLint("UnusedBoxWithConstraintsScope")
 2@Composable
 3fun EjemploBoxWithConstraints() {
 4    BoxWithConstraints(
 5        modifier = Modifier
 6            .fillMaxWidth()
 7            .height(200.dp)
 8            .background(Color.LightGray)
 9    ) {
10        val isPantallaGrande = maxWidth > 300.dp
11
12        Box(
13            modifier = Modifier
14                .fillMaxSize()
15                .background(if (isPantallaGrande) Color.Cyan else Color.Magenta),
16            contentAlignment = Alignment.Center
17        ) {
18            Text(
19                text = if (isPantallaGrande) "Pantalla ancha" else "Pantalla estrecha",
20                fontSize = 20.sp,
21                color = Color.White
22            )
23        }
24    }
25}

Para visualizar el ejemplo en la vista previa de Android Studio añade los siguientes métodos, ajustando los anchos de pantalla:

 1@Preview(showBackground = true, widthDp = 400)
 2@Composable
 3fun VistaPreviaPantallaAncha() {
 4    EjemploBoxWithConstraints()
 5}
 6
 7@Preview(showBackground = true, widthDp = 250)
 8@Composable
 9fun VistaPreviaPantallaEstrecha() {
10    EjemploBoxWithConstraints()
11}