Lazy Composables en Android Jetpack Compose: columnas, filas, cuadrículas

En Jetpack compose tenemos Composables como Columna y Fila , pero cuando la aplicación necesita mostrar una gran cantidad de elementos en una fila o columnas, no es eficiente si se hace mediante Fila o Columna Componible. Por lo tanto, tenemos Lazy Composables en Jetpack Compose. Principalmente tenemos tres tipos de Lazy Composables Row, Column y Grid. En este artículo, vamos a ver los tres Lazy Composables. Construiremos una aplicación simple que demuestre los tres componibles en acción.

requisitos previos:

Implementación paso a paso

Paso 1: cree un nuevo proyecto (o utilícelo en el proyecto Compose existente)

Para crear un nuevo proyecto en la versión Android Studio Canary, consulte el artículo Cómo crear un nuevo proyecto en la versión Android Studio Canary con Jetpack Compose.

Paso 2: Agregar color ( opcional)

Abra ui> tema> Colors.kt y agregue 

valor GreenGfg = Color (0xFF0F9D58)

Paso 3: Cree elementos de fila y columna que se mostrarán

Abra MainActivity.kt y cree dos Composables, uno para el elemento de fila y otro para el elemento de columna

Kotlin

// Row Item with item Number 
@Composable
fun RowItem(number: Int) {
  
    // Simple Row Composable
    Row(
        modifier = Modifier
            .size(100.dp) // Size 100 dp
            .background(Color.White) // Background White
            .border(1.dp, GreenGfg), // Border color green
  
        // Align Items in Center
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.Center
  
    ) {
        // Text Composable which displays some 
        // kind of message , text color is green
        Text(text = "This Is Item Number $number", color = GreenGfg)
    }
}
  
// Similar to row composable created above
@Composable
fun ColumnItem(number: Int) {
  
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .height(30.dp)
            .background(Color.White)
            .border(1.dp, GreenGfg),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
  
    ) {
        Text(text = "This Is Item Number $number", color = GreenGfg)
    }
}

Paso 4: Trabajando con Lazy Composables

Unline Column o Row Composable no podemos colocar composable dentro directamente dentro de Lazy Composables. Lazy Composables proporciona funciones para colocar elementos en LazyScope. Hay principalmente cinco funciones sobrecargadas. 

Función

Parámetro

Funcionalidad

artículo componible Coloca un elemento en el LazyScope
elementos cuenta, clave (opcional), componible Los lugares cuentan elementos en el LazyScope
elementos Lista, Componible Coloca el número de elementos presentes igual que el tamaño de la Lista,
elementos Array, componible Coloca el número de elementos presentes igual que el tamaño de Array,
elementos indexados Array/Lista, Componible

Coloca el número de elementos presentes igual que el tamaño de Array,

y proporciona el artículo (en la lista) y el índice del artículo actual.

Paso 4.1: fila perezosa

Cree un Composable en MainActivity.kt, aquí colocaremos Lazy Row para demostrar Lazy Row

Kotlin

@Composable
fun LazyRowExample(numbers: Array<Int>) {
  
    // Place A lazy Row
    LazyRow(
        contentPadding = PaddingValues(8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
  
        // item places one item on the LazyScope
        item {
            RowItem(number = 0)
        }
  
        // items(count) places number of items supplied
        // as count and gives current count in the lazyItemScope
        items(10) {currentCount->
            RowItem(number = currentCount)
        }
  
        // items(list/array) places number of items same as
        // the size of list/array and gives current list/array
        // item in the lazyItemScope
        items(numbers) {arrayItem-> // Here numbers is Array<Int> so we 
                                      // get Int in the scope.
            RowItem(number = arrayItem)
        }
  
        // items(list/array) places number of items same 
        // as the size of list/array and gives current list/array 
        // item and currentIndex in the lazyItemScope
        itemsIndexed(numbers) { index: Int, item: Int ->
            RowItem(number = index)
        }
    }
}

 Paso 4.2: Columna perezosa

Cree un Composable en MainActivity .kt, aquí colocaremos Lazy Column para demostrar Lazy Column

Kotlin

@Composable
fun ColumnExample(numbers: Array<Int>) {
  
    LazyColumn(
        contentPadding = PaddingValues(8.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        // item places one item on the LazyScope
        item {
            ColumnItem(number = 0)
        }
  
        // items(count) places number of items supplied 
        // as count and gives current count in the lazyItemScope
        items(10) {currentCount->
            ColumnItem(number = currentCount)
        }
  
        // items(list/array) places number of items same
        // as the size of list/array and gives current 
        // list/array item in the lazyItemScope
        items(numbers) {arrayItem->
            ColumnItem(number = arrayItem)
        }
  
        // items(list/array) places number of items 
        // same as the size of list/array and gives
        // current list/array item and currentIndex 
        // in the lazyItemScope
        itemsIndexed(numbers) { index, item ->
            ColumnItem(number = index)
        }
    }
}

Paso 4.3: Cuadrícula perezosa

Cree un Composable en MainActivity.kt, aquí colocaremos LazyVerticalGrid. Es casi lo mismo que otros complementos perezosos, pero requiere celdas de parámetros adicionales, que es la cantidad de elementos de cuadrícula en una fila / ancho mínimo de un elemento. las celdas pueden ser GridCells.Fixed(count) , corrige los elementos que se muestran en una fila de cuadrícula. Otro valor que acepta es GridCells.Adaptive(minWidth), establece el minWidth de cada elemento de la cuadrícula.

Kotlin

// add the annotation, 
// since [LazyVerticalGrid] is Experimental Api
@ExperimentalFoundationApi
@Composable
fun GridExample(numbers: Array<Int>) {
    // Lazy Vertical grid
    LazyVerticalGrid(
        // fix the item in one row to be 2.
        cells = GridCells.Fixed(2),
  
        contentPadding = PaddingValues(8.dp),
  
        ) {
        item {
            RowItem(number = 0)
        }
        items(10) {
            RowItem(number = it)
        }
        items(numbers) {
            RowItem(number = it)
        }
        itemsIndexed(numbers) { index, item ->
            RowItem(number = index)
        }
    }
}

Paso 5: Colocando los Componibles en la Pantalla

Ahora coloque los tres ejemplos en setContentView en MainActivity Class.

Kotlin

class MainActivity : ComponentActivity() {
  
    // Creates array as [0,1,2,3,4,5,.....99]
    private val numbers: Array<Int> = Array(100) { it + 1 }
  
    @ExperimentalFoundationApi
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            LazyComponentsTheme {
  
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(Color.White)
                ) {
                    // Place the row and column 
                    // to take 50% height of screen
                    Column(Modifier.fillMaxHeight(0.5f)) {
                          
                        // Heading
                        Text(
                            text = "Row",
                            color = Color.Black,
                            modifier = Modifier.padding(start = 8.dp)
                        )
                          
                        // Lazy Row, pass the numbers array
                        LazyRowExample(numbers = numbers)
                          
                        // Heading
                        Text(
                            text = "Column",
                            color = Color.Black,
                            modifier = Modifier.padding(start = 8.dp)
                        )
                        // Lazy Column, Pass the numbers array
                        LazyColumnExample(numbers = numbers)
                    }
                      
                    Column(Modifier.fillMaxHeight()) {
                          
                        // Heading
                        Text(
                            text = "Grid",
                            color = Color.Black,
                            modifier = Modifier.padding(start = 8.dp)
                        )
                          
                        // Lazy Grid
                        GridExample(numbers = numbers)
                    }
                }
            }
        }
    }
}

Código completo: 

Nota : antes de ejecutar todo este código, asegúrese de realizar el Paso 2 o reemplace GreenGfg con su propio color.

Kotlin

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.gfg.lazycomponents.ui.theme.GreenGfg
import com.gfg.lazycomponents.ui.theme.LazyComponentsTheme
  
class MainActivity : ComponentActivity() {
  
    // Creates array as [0,1,2,3,4,5,.....99]
    private val numbers: Array<Int> = Array(100) { it + 1 }
  
    @ExperimentalFoundationApi
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            LazyComponentsTheme {
  
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(Color.White)
                ) {
                    // Place the row and column
                    // to take 50% height of screen
                    Column(Modifier.fillMaxHeight(0.5f)) {
  
                        // Heading
                        Text(
                            text = "Row",
                            color = Color.Black,
                            modifier = Modifier.padding(start = 8.dp)
                        )
  
                        // Lazy Row,pass the numbers array
                        LazyRowExample(numbers = numbers)
  
                        // Heading
                        Text(
                            text = "Column",
                            color = Color.Black,
                            modifier = Modifier.padding(start = 8.dp)
                        )
                        // Lazy Column, Pass the numbers array
                        LazyColumnExample(numbers = numbers)
                    }
  
                    Column(Modifier.fillMaxHeight()) {
  
                        // Heading
                        Text(
                            text = "Grid",
                            color = Color.Black,
                            modifier = Modifier.padding(start = 8.dp)
                        )
  
                        // Lazy Grid
                        GridExample(numbers = numbers)
                    }
                }
            }
        }
    }
}
  
  
@Composable
fun LazyRowExample(numbers: Array<Int>) {
    // Place A lazy Row
    LazyRow(
        contentPadding = PaddingValues(8.dp),
          
        // Each Item in LazyRow have a 8.dp margin
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
  
        // item places one item on the LazyScope
        item {
            RowItem(number = 0)
        }
  
        // items(count) places number of items supplied
        // as count and gives current count in the lazyItemScope
        items(10) {currentCount->
            RowItem(number = currentCount)
        }
  
        // items(list/array) places number of items 
        // same as the size of list/array and gives 
        // current list/array item in the lazyItemScope
        items(numbers) {arrayItem-> // Here numbers is Array<Int> so we 
                                      // get Int in the scope.
            RowItem(number = arrayItem)
        }
  
        // items(list/array) places number of items 
        // same as the size of list/array and gives
        // current list/array item and currentIndex
        // in the lazyItemScope
        itemsIndexed(numbers) { index: Int, item: Int ->
            RowItem(number = index)
        }
    }
}
  
  
@Composable
fun RowItem(number: Int) {
    // Simple Row Composable
    Row(
        modifier = Modifier
            .size(100.dp) // Size 100 dp
            .background(Color.White) // Background White
            .border(1.dp, GreenGfg), // Border color green
  
        // Align Items in Center
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.Center
    ) {
        // Text Composable which displays some 
        // kind of message , text color is green
        Text(text = "This Is Item Number $number", color = GreenGfg)
    }
}
  
@Composable
fun ColumnItem(number: Int) {
  
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .height(30.dp)
            .background(Color.White)
            .border(1.dp, GreenGfg),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
  
    ) {
        Text(text = "This Is Item Number $number", color = GreenGfg)
    }
}
  
@Composable
fun LazyColumnExample(numbers: Array<Int>) {
    LazyColumn(
        contentPadding = PaddingValues(8.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        // item places one item on the LazyScope
        item {
            ColumnItem(number = 0)
        }
  
        // items(count) places number of items supplied 
        // as count and gives current count in the lazyItemScope
        items(10) {currentCount->
            ColumnItem(number = currentCount)
        }
  
        // items(list/array) places number of items
        // same as the size of list/array and gives 
        // current list/array item in the lazyItemScope
        items(numbers) {arrayItem->
            ColumnItem(number = arrayItem)
        }
  
        // items(list/array) places number of 
        // items same as the size of list/array 
        // and gives current list/array item and 
        // currentIndex in the lazyItemScope
        itemsIndexed(numbers) { index, item ->
            ColumnItem(number = index)
        }
    }
}
  
  
// add the annotation, 
// since [LazyVerticalGrid] is Experimental Api
@ExperimentalFoundationApi
@Composable
fun GridExample(numbers: Array<Int>) {
    // Lazy Vertical grid
    LazyVerticalGrid(
        
        // fix the item in one row to be 2.
        cells = GridCells.Fixed(2),
  
        contentPadding = PaddingValues(8.dp),
  
        ) {
        item {
            RowItem(number = 0)
        }
        items(10) {
            RowItem(number = it)
        }
        items(numbers) {
            RowItem(number = it)
        }
        itemsIndexed(numbers) { index, item ->
            RowItem(number = index)
        }
    }
}

Ahora ejecute la aplicación en un emulador o teléfono.

Producción:

Obtenga el código completo de GitHub .

Publicación traducida automáticamente

Artículo escrito por sunny52525 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *