La vista de cuadrícula escalonada se ha visto en la mayoría de las aplicaciones, como Pinterest, en la que cada elemento de la vista de cuadrícula toma su propia altura y se alinea dentro de la vista de cuadrícula de acuerdo con eso. En este artículo, veremos cómo implementar Vista de cuadrícula escalonada en Android usando Jetpack Compose
Implementación paso a paso
Paso 1: crea un nuevo proyecto en Android Studio
Para crear un nuevo proyecto en Android Studio, consulte Cómo crear/iniciar un nuevo proyecto en Android Studio . Al elegir la plantilla, seleccione Actividad de composición vacía . Si no encuentra esta plantilla, intente actualizar Android Studio a la última versión. Demostramos la aplicación en Kotlin, así que asegúrese de seleccionar Kotlin como idioma principal al crear un nuevo proyecto.
Paso 2: Agregar un nuevo color en el archivo Color.kt
Vaya a la aplicación > java > el nombre del paquete de su aplicación > ui.theme > archivo Color.kt y agréguele el siguiente código.
Kotlin
package com.example.newcanaryproject.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFF0F9D58) val Purple500 = Color(0xFF0F9D58) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5) // on below line we are adding different colors. val greenColor = Color(0xFF0F9D58)
Paso 3: agregar imágenes a la carpeta dibujable
Copie todas las imágenes que desee agregar a su vista de cuadrícula. Vaya a aplicación > res > dibujable. Haga clic derecho sobre él y pegue todas las imágenes en la carpeta dibujable.
Paso 4: trabajar con el archivo MainActivity.kt
Vaya al archivo MainActivity.kt y consulte el siguiente código. A continuación se muestra el código del archivo MainActivity.kt . Se agregan comentarios dentro del código para comprender el código con más detalle.
Kotlin
package com.example.newcanaryproject import android.content.Context import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.GridCells import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyVerticalGrid import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.Layout import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.* import coil.compose.rememberAsyncImagePainter import com.example.newcanaryproject.ui.theme.* import java.util.* class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { NewCanaryProjectTheme { // on below line we are specifying // background color for our application Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { // on below line we are specifying theme as scaffold. Scaffold( // in scaffold we are specifying top bar. topBar = { // inside top bar we are specifying background color. TopAppBar(backgroundColor = greenColor, // along with that we are specifying title for our top bar. title = { // in the top bar we are specifying tile as a text Text( // on below line we are specifying // text to display in top app bar. text = "Staggered Grid View Example", // on below line we are specifying // modifier to fill max width. modifier = Modifier.fillMaxWidth(), // on below line we are specifying text alignment. textAlign = TextAlign.Center, // on below line we are specifying // color for our text. color = Color.White ) } ) } ) { // on below line we are calling custom list // view function to display custom listview. StaggeredGridView() } } } } } } @Composable fun StaggeredGridView() { // on below line we are creating // an array of images. val images = listOf( R.drawable.imgone, R.drawable.imgtwo, R.drawable.imgthree, R.drawable.imgfour, R.drawable.imgfive, R.drawable.imgsix, R.drawable.imgseven, R.drawable.imgeight, R.drawable.imgnine, R.drawable.imgten ) // on below line we are creating a column // for our staggered grid view. Column( // for this column we are adding a // modifier to it to fill max size. modifier = Modifier .fillMaxSize() ) { // on below line we are creating a column // for each item of our staggered grid. Column( // in this column we are adding modifier to it // and adding padding from all sides and vertical scroll. modifier = Modifier .verticalScroll(rememberScrollState()) .padding(5.dp) ) { // on below line we are calling our // custom staggered vertical grid item. CustomStaggeredVerticalGrid( // on below line we are specifying // number of columns for our grid view. numColumns = 2, // on below line we are adding padding // from all sides for our grid view. modifier = Modifier.padding(5.dp) ) { // inside staggered grid view we are // adding images for each item of grid. images.forEach { img -> // on below line inside our grid // item we are adding card. Card( // on below line inside the card we // are adding modifier to it to specify // max width, padding, elevation and shape for the card modifier = Modifier .fillMaxWidth() .padding(5.dp), elevation = 10.dp, shape = RoundedCornerShape(10.dp) ) { // on below line we are adding column inside our card. Column( // in this column we are adding modifier // to fill max size and align our // card center horizontally. modifier = Modifier .fillMaxSize() .align(Alignment.CenterHorizontally), horizontalAlignment = Alignment.CenterHorizontally ) { // inside our column we are creating an image. Image( // on below line we are specifying the // drawable image for our image. painterResource(id = img), // on below line we are specifying // content description for our image contentDescription = "images", // on below line we are specifying // alignment for our image. alignment = Alignment.Center, ) } } } } } } } // on below line we are creating a custom // composable item for our grid view item. @Composable fun CustomStaggeredVerticalGrid( // on below line we are specifying // parameters as modifier, num of columns modifier: Modifier = Modifier, numColumns: Int = 2, content: @Composable () -> Unit ) { // inside this grid we are creating // a layout on below line. Layout( // on below line we are specifying // content for our layout. content = content, // on below line we are adding modifier. modifier = modifier ) { measurable, constraints -> // on below line we are creating a variable for our column width. val columnWidth = (constraints.maxWidth / numColumns) // on the below line we are creating and initializing our items constraint widget. val itemConstraints = constraints.copy(maxWidth = columnWidth) // on below line we are creating and initializing our column height val columnHeights = IntArray(numColumns) { 0 } // on below line we are creating and initializing placebles val placeables = measurable.map { measurable -> // inside placeble we are creating // variables as column and placebles. val column = testColumn(columnHeights) val placeable = measurable.measure(itemConstraints) // on below line we are increasing our column height/ columnHeights[column] += placeable.height placeable } // on below line we are creating a variable for // our height and specifying height for it. val height = columnHeights.maxOrNull()?.coerceIn(constraints.minHeight, constraints.maxHeight) ?: constraints.minHeight // on below line we are specifying height and width for our layout. layout( width = constraints.maxWidth, height = height ) { // on below line we are creating a variable for column y pointer. val columnYPointers = IntArray(numColumns) { 0 } // on below line we are setting x and y for each placeable item placeables.forEach { placeable -> // on below line we are calling test // column method to get our column index val column = testColumn(columnYPointers) placeable.place( x = columnWidth * column, y = columnYPointers[column] ) // on below line we are setting // column y pointer and incrementing it. columnYPointers[column] += placeable.height } } } } // on below line we are creating a test column method for setting height. private fun testColumn(columnHeights: IntArray): Int { // on below line we are creating a variable for min height. var minHeight = Int.MAX_VALUE // on below line we are creating a variable for column index. var columnIndex = 0 // on below line we are setting column height for each index. columnHeights.forEachIndexed { index, height -> if (height < minHeight) { minHeight = height columnIndex = index } } // at last we are returning our column index. return columnIndex }
Ejecute su aplicación para ver el resultado de la misma.
Producción:
Publicación traducida automáticamente
Artículo escrito por chaitanyamunje y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA