Jetpack Compose

Lists using LazyColumn in Jetpack Compose

Lists using LazyColumn within Jetpack Compose. Prior to Jetpack Compose made use of LazyColumn, we were able to build the RecyclerView as well as an Adapter to display a huge list of lists. Today, we can make use of LazyColumn as well as LazyRow to display a huge list of lists either vertically or horizontally, using only a few lines of code, as we’ll demonstrate in this article.

What will you build?

To better understand the subject the concept, we’ll create an application that will display an array of fruit kart.

Step 1: Create the app

Launch the latest version of Android Studio -> new project, then select “Empty Compose Activity” from tablets and phones -then type in [your project’s name[your project’s name].

Step 2. Add fake data to the display

First, you must create an Fruit data class with an ID and a name, as well as a description and images as a resource. The image resource is an integer because we’ll be referencing the ID of the image using R class.

Begin to create your data class creating the new Kotlin class/file, then data class and then Plant. The data class must contain the following code

create a brand new Kotlin class/file, then File -> Fruit.

data class Fruit(
    val id: Int,
    val name: String,
    val description: String,
    val imageRes: Int
)

 Within this file you can copy the below listing of plant species below. There will be an unresolved reference error within the value of imageRes. This will be removed after importing the images that correspond to them during the subsequent step.

 download the images of the Fruit. In Android Studio, go to the “Resource Manager” -> under the tab for drawable. And Copy past your image in drawable folder.

Lists using LazyColumn in Jetpack Compose

MainActivity.kt

Let’s return to “MainActivity”and remove the “Greeting” function and its call-outs from the theme for the app as well as the preview feature.

“AllFruits” Composable “AllFruits” Composable which you will announce in a minute. You must pass to the “Fruits” list inside “AllFruits”. It will look like this:

package com.codeplayon.fruitskart.ui

import android.content.res.Configuration
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.tooling.preview.Preview
import com.codeplayon.fruitskart.model.fruits
import com.codeplayon.fruitskart.ui.theme.PlantsInCosmeticsTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            PlantsInCosmeticsTheme {
                window.statusBarColor = MaterialTheme.colors.primaryVariant.toArgb()
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                    AllPlants(fruits)
                }
            }
        }
    }
}

 

AllFruits.kt for Lists using LazyColumn

Create a new Kotlin class/file , then File -> AllFruits

In that file, you should write “AllFruits” composable function that takes an array of Fruits to display in the future using LazyColumn. Your code should look like this:

In this case we’d like to have a standard bar for the app that displays the app’s name. And, underneath we would like to see the list of plants along with their contact information.

To accomplish this, we’ll make use of “Scaffold” composable which allows us to split the screen into app bars as well as a body-content.

Scaffold Composable is a topBar parameter, which is an able function. In this case, utilize the already defined TopAppBar composable function, which uses parameters to determine what and how it displays it.

To create the screen above to implement the above screen, we’ll make use of “item” inside LazyColumn and create a row that will take the rest of the width with a vertical the padding to 25.dp.

Rows permit us to arrange content within them towards the end of the row, at the beginning or in the middle. We can also specify a horizontalArrangement which is the horizontal arrangement of the row children, and a verticalAlignment which is the vertical alignment of the row children. This should be an aligned value. Your code should appear like this:

In addition to items inside LazyColumn it is possible to define items using the form of a list of data and then display every list element as an encapsulated. The plant list that is generated by MainActivity to MainActivity as a list of data for the items().

In each case, we’ll show the details in the form of a PlantCard which is a custom composable document that we will create at the end of the process.

Within PlantCard In PlantCard, we must send the plant’s names, descriptions, as well as the image to show the information. Following the steps we have discussed the code should appear as follows:

package com.codeplayon.fruitskart.ui

import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.codeplayon.fruitskart.R
import com.codeplayon.fruitskart.model.data.Fruit

@Composable
fun AllPlants (platList: List<Fruit>){
    Scaffold(
        topBar = {
            TopAppBar(
                backgroundColor = MaterialTheme.colors.primary,
                title = { Text(stringResource(R.string.app_name)) }
            )
        }
    ) {
        LazyColumn(
            Modifier.fillMaxWidth(),
            contentPadding = PaddingValues(16.dp)
        ) {
            items(platList){ plant ->
                PlantCard(plant.name, plant.description, plant.imageRes)
            }
        }
    }
}

FruitCard.kt

Create a new Kotlin class or file -> file > FruitCard

In that file, you write “FruitCard” composable function using the parameters we used previously in AllPlant file. As an example:

For the design above using the Card compatible. The appearance for this card by using a Modifier to create a 10.dp padding from every side and to include the width that is left after padding.

For length, we will employ wrap content as certain cards contain more content than others.

To determine the card’s shape you should choose the shapes provided by MaterialTheme that we can modify later in the article. Let’s start by choosing the medium-sized shape.

Elevation determines the dimension of the shadow beneath the card. Let’s use 5.dp to control the parameter elevation.

We must also define the background color of the card to use an amount from MaterialTheme that we will discuss customization in the next article.

Images() and an array(). It displays two words vertically , the name and descriptions of the plant.

Let’s begin by introducing the Image composable, which shows pictures on your screen. It takes a painter parameter -for png and jpg- which can be a hardcoded value of an image or it can be retrieved from the resources folder using painterResource(image). We already have the imageRes ID to AllPlants therefore we can apply it here.

A contentDescription is essential to ensure accessibility.

Also, we must specify the dimensions of the image in order to ensure it’s displayed properly. Let’s say we want to give it a 130.dp size, and an 8.dp padding with a the Modifier.

contentScale must be FIT to display the entire image within the size specified. The image code should be like this:

FruitCard Full Source Code 

package com.codeplayon.fruitskart.ui

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material.Card
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp


@Composable
fun PlantCard(name: String, description: String, image: Int) {
    Card(
        modifier = Modifier
            // The space between each card and the other
            .padding(10.dp)
            .fillMaxWidth()
            .wrapContentHeight(),
        shape = MaterialTheme.shapes.medium,
        elevation = 5.dp,
        backgroundColor = MaterialTheme.colors.surface
    ) {
        Column(
            Modifier.padding(8.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Image(
                painter = painterResource(id = image),
                contentDescription = null,
                modifier = Modifier
                    .size(130.dp)
                    .padding(8.dp),
                contentScale = ContentScale.Fit,
            )
            Text(
                text = name,
                style = TextStyle(fontSize =25.sp),
                modifier = Modifier
                    .padding(bottom = 8.dp)
                    .fillMaxWidth(),
                color = MaterialTheme.colors.onSurface,
            )
            Text(
                text = description,
                style = MaterialTheme.typography.body1,
                modifier = Modifier.padding(bottom = 4.dp)
            )

        }
    }
}

 

Now create a new kotlin file with the name Fruits.kt for data for follow code

Fruits.kt

package com.codeplayon.fruitskart.model

import com.codeplayon.fruitskart.R
import com.codeplayon.fruitskart.model.data.Fruit

val fruits = listOf(
    Fruit(
        1,
        "Apple",
        "It is used in the pharmaceutical industry for its healing properties and it can often be found in several cosmetic products as well.",
        R.drawable.apple_min,
    ),
    Fruit(
        2,
        "Avocado",
        "Rose is a valuable natural cosmetic ingredient. It contains antibacterial and antioxidants. It's toning and relaxing.",
        R.drawable.avocado_min,
    ),
    Fruit(
        3,
        "Banana",
        "Calendula helps reducing redness and healing up the skin and it is considered a medicinal plant.",
        R.drawable.banana_min,
    ),
    Fruit(
        4,
        "Grapes",
        "The lavender blossoms contain nurturing essential oils for the skin which have a balancing and soothing fragrance.",
        R.drawable.grapes_min,
    ),
    Fruit(
        5,
        "KIWI",
        "Jojoba improves skin elasticity and prevents skin dehydration, making it perfect for sensitive or very dry skin.",
        R.drawable.kiwi_fruit_min,
    ),
    Fruit(
        6,
        "Orange",
        "Tea tree is aimed to fight against acne and to treat acne prone skin. It’s considered one of the best natural alternatives to chemical substances.",
        R.drawable.orange_min,
    ),
    Fruit(
        7,
        "Papaya",
        "Chamomile is the most extensive applications in natural cosmetics. It is a common flavoring agent in foods and beverages, and other products such as mouthwash, soaps, and cosmetics.",
        R.drawable.papaya_min,
    ),
    Fruit(
        8,
        "Peach",
        "Rosemary (Rosmarinus officinalis) is deep green in colour and pungent in fragrance.",
        R.drawable.peach_min,
    ),
    Fruit(
        9,
        "Pineapple",
        "It contains high amounts of vitamin C and a potent antioxidant that can protect the skin from free radicals, stimulate collagen production, and reduce hyper pigmentation.",
        R.drawable.pineapple_min,
    ),
    Fruit(
        10,
        "pomegranate",
        "Cilantro is high in vitamin C, an antioxidant that fights off damage-causing free radicals.",
        R.drawable.pomegranate_min,
    ),
    Fruit(
        11,
        "Orange",
        "Consuming enough vitamin C can help a person maintain skin health and appearance.  Vitamin C contributes to collagen production. Collagen supports the skin, promotes wound healing, and improves skin strength.",
        R.drawable.orange_min,
    ),
    Fruit(
        12,
        "Apple",
        "Cucumber is rich in all most Vitamin (C,A,B,K). Magnesium in cucumbers can promote skin elasticity and retain skin moisture.Potassium in cucumbers is another mineral that can help in hydrating the skin and balancing the electrolytes.",
        R.drawable.apple_min,
    ),
)


Read More Tutorial