0
0
Android Kotlinmobile~5 mins

LazyColumn for lists in Android Kotlin

Choose your learning style9 modes available
Introduction

LazyColumn helps you show a long list of items on the screen without slowing down your app. It only draws what you see, saving memory and making scrolling smooth.

When you want to show a list of messages in a chat app.
When displaying a list of contacts or friends.
When showing a list of products in a shopping app.
When you have many items but want to load them efficiently as the user scrolls.
Syntax
Android Kotlin
LazyColumn {
    items(listOfItems) { item ->
        Text(text = item)
    }
}

LazyColumn is a composable that shows a vertical scrolling list.

The items function takes a list and a lambda to show each item.

Examples
Shows a list of fruits with simple text for each.
Android Kotlin
LazyColumn {
    items(listOf("Apple", "Banana", "Cherry")) { fruit ->
        Text(text = fruit)
    }
}
Handles the case when the list is empty. Nothing will be shown.
Android Kotlin
LazyColumn {
    items(emptyList<String>()) { item ->
        Text(text = item)
    }
}
Shows a list with just one item.
Android Kotlin
LazyColumn {
    items(listOf("Only one item")) { item ->
        Text(text = item)
    }
}
Sample App

This program shows a vertical scrolling list of fruit names using LazyColumn. Each fruit name is shown as text. The list fills the available screen space.

Android Kotlin
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview

@Composable
fun FruitList() {
    val fruits = listOf("Apple", "Banana", "Cherry", "Date", "Elderberry")
    LazyColumn(modifier = Modifier.fillMaxSize()) {
        items(fruits) { fruit ->
            Text(text = fruit, style = MaterialTheme.typography.bodyLarge)
        }
    }
}

@Preview(showBackground = true)
@Composable
fun FruitListPreview() {
    Surface {
        FruitList()
    }
}
OutputSuccess
Important Notes

LazyColumn only creates items that are visible on screen, so it uses less memory and is faster than a regular Column for long lists.

Time complexity for displaying items is O(n) where n is visible items, not the whole list.

Common mistake: Using a regular Column for long lists can cause slow app and crashes due to memory.

Use LazyColumn when you have many items or an unknown number of items to show efficiently.

Summary

LazyColumn shows vertical lists efficiently by creating only visible items.

Use it for long or dynamic lists to keep your app smooth and fast.

Remember to pass your list to items inside LazyColumn to display each element.