How do I display tasks in a LazyColumn with Jetpack Compose?

Android Programming Essentials

In article 2, you created a Task model and three sample tasks. The screen displayed only the first task. In this article, you will display the entire collection as a scrolling list and create a reusable component for each task.

Continue with the same Task Notes project, package org.kodejava.tasknotes, and generated TaskNotesTheme. Keep Task.kt and SampleTasks.kt from the previous article unchanged.

1. Choose a layout for the list

Column arranges composables vertically. LazyColumn provides a vertically scrolling list whose items are composed and laid out as needed. It also supports prefetching, so avoid assuming that only the exact visible rows can exist in composition.

Three fixed rows could fit in a regular Column. We use LazyColumn because Task Notes will eventually contain a growing collection of user-created tasks. See the official lazy lists documentation.

We will keep the screen title above the list so that it remains visible while the tasks scroll.

2. Replace MainActivity.kt

Replace MainActivity.kt with the complete example below. If you use another package or generated theme name, adjust those declarations and imports.

File: app/src/main/java/org/kodejava/tasknotes/MainActivity.kt

package org.kodejava.tasknotes

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import org.kodejava.tasknotes.data.sampleTasks
import org.kodejava.tasknotes.model.Task
import org.kodejava.tasknotes.ui.theme.TaskNotesTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        setContent {
            TaskNotesTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    TaskNotesScreen(
                        tasks = sampleTasks(),
                        modifier = Modifier.padding(innerPadding)
                    )
                }
            }
        }
    }
}

@Composable
private fun TaskNotesScreen(
    tasks: List<Task>,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier.fillMaxSize(),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Text(
            text = "Task Notes",
            style = MaterialTheme.typography.headlineMedium,
            modifier = Modifier.padding(
                start = 24.dp,
                top = 24.dp,
                end = 24.dp
            )
        )
        Text(
            text = "Tasks: ${tasks.size}",
            style = MaterialTheme.typography.bodyMedium,
            modifier = Modifier.padding(horizontal = 24.dp)
        )

        if (tasks.isEmpty()) {
            Text(
                text = "No tasks yet.",
                modifier = Modifier.padding(24.dp)
            )
        } else {
            LazyColumn(
                modifier = Modifier.fillMaxWidth().weight(1f),
                contentPadding = PaddingValues(
                    horizontal = 24.dp,
                    vertical = 16.dp
                ),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                items(
                    items = tasks,
                    key = { task -> task.id }
                ) { task ->
                    TaskRow(task = task)
                }
            }
        }
    }
}

@Composable
private fun TaskRow(
    task: Task,
    modifier: Modifier = Modifier
) {
    Card(modifier = modifier.fillMaxWidth()) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(6.dp)
        ) {
            Text(
                text = task.title,
                style = MaterialTheme.typography.titleMedium
            )
            Text(
                text = if (task.isCompleted) "Completed" else "Not completed",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

@Preview(showBackground = true)
@Composable
private fun TaskNotesScreenPreview() {
    TaskNotesTheme {
        TaskNotesScreen(tasks = sampleTasks())
    }
}

@Preview(showBackground = true)
@Composable
private fun EmptyTaskNotesScreenPreview() {
    TaskNotesTheme {
        TaskNotesScreen(tasks = emptyList())
    }
}

weight(1f) is available here through the surrounding Column scope. You do not need to add a separate weight import for this example.

3. Read the list code

The screen now accepts tasks: List<Task> as an argument. Its caller supplies sample data, while the screen describes how to display it. The same screen can therefore show the original samples, an empty list, or a larger collection without changing its implementation.

Inside LazyColumn, items() describes the repeated content:

items(
    items = tasks,
    key = { task -> task.id }
) { task ->
    TaskRow(task = task)
}

The items argument is the collection. The final lambda receives one task and describes its row. Import androidx.compose.foundation.lazy.items to use the collection overload.

Each key identifies an item across list changes. Our model’s distinct Long IDs remain suitable even when titles change or tasks move. Do not use the title as a key: two tasks can have the same title. A key must remain stable for that task and be unique within the list.

Keys do not save task data to disk or make a read-only list interactive. We will introduce observable state in the next article.

4. Understand the row and spacing

TaskRow() receives one Task and displays its title and status inside a Material 3 Card. The status uses words, so the user does not have to interpret a color to know whether a task is completed.

The row has no click handler or checkbox yet. Completion still comes from the values in SampleTasks.kt.

The layout uses several kinds of spacing:

Code Purpose
Modifier.padding(innerPadding) Keeps screen content clear of system bars through the existing Scaffold
weight(1f) Gives the list the remaining height below the header
contentPadding Adds space before, after, and beside the scrolling rows
Arrangement.spacedBy(12.dp) Adds space between task cards
Modifier.padding(16.dp) Adds space inside each card

Do not wrap this screen in a vertically scrolling Column. The list already scrolls, and it needs a bounded height. Here, the activity supplies the screen bounds and weight(1f) allocates the remaining space to the list.

5. Check the screen

Run the app on your emulator or phone. It should show Task Notes, Tasks: 3, and these cards:

Title Status
Learn Kotlin basics Not completed
Create the Task model Completed
Build the task list Not completed

All three cards may fit without scrolling. To check scrolling, temporarily replace tasks = sampleTasks() in MainActivity.onCreate() with:

tasks = List(50) { index ->
    Task(
        id = index.toLong() + 1L,
        title = "Practice task ${index + 1}",
        isCompleted = index % 3 == 0
    )
},

Keep the following modifier argument. Kotlin’s List(50) creates fifty elements using indexes from zero to forty-nine. Each generated task receives a different ID. The % operator returns the remainder, so indexes divisible by three produce completed tasks.

Run again, scroll to Practice task 50, and confirm that the header stays above the scrolling list. Restore tasks = sampleTasks() afterward.

To check the empty state, temporarily pass emptyList() instead. The count should become zero and the screen should show No tasks yet. Restore the original samples when finished.

The two preview functions also let you inspect populated and empty screens. This article’s Android build and device behavior have not been executed in an Android SDK environment; the checks above are steps to perform in your project.

Troubleshooting

  • If items expects an integer instead of your list, check the androidx.compose.foundation.lazy.items import.
  • If Compose reports duplicate keys, check that every task has a distinct ID. Repeating the same sample list without changing IDs creates duplicates.
  • If scrolling fails with an infinite-height constraint error, remove an outer vertical scroll container and keep the bounded layout shown above.
  • If your generated theme has another name, use that name in both the activity and previews.

Practice

  1. Add a fourth sample task with ID 4L and verify the count and new card.
  2. Give one task a longer title. Check that it wraps without hiding the status.
  3. Change the card spacing from 12.dp to 20.dp and compare the result.

Restore the original three samples before continuing.

Gradle dependencies and compatibility

No additional Gradle dependencies are required when continuing from articles 1 and 2. The example uses the existing Compose Foundation, Material 3, and preview dependencies.

Keep the plugin versions, Compose BOM, and version catalog generated for your working project. This lesson does not require a dependency upgrade. For configuration details, refer to the official Compose setup guide.

References

Next in the series

In article 4, How Do I Update Task Completion with State in Jetpack Compose?, you will add a checkbox and update a task’s completion status using observable state and copy().

How do I use Kotlin to model tasks in an Android app?

Android Programming Essentials

In article 1, you created Task Notes and its empty screen. Now you will describe the data behind a task using Kotlin. You will create a Task model, prepare sample tasks, and display one task on the existing screen. The next article will turn those samples into a scrolling list.

Practical goal

By the end, you will be able to declare typed properties, use default and named arguments, create a read-only list, and produce an updated task with copy().

Continue with the same Android Studio project. This example keeps the package org.kodejava.tasknotes, the generated TaskNotesTheme, and minimum SDK API 24 from article 1. If you used your own package, adjust the package declarations and imports below.

1. Create the Task model

Create the model package below org.kodejava.tasknotes. Add this file:

File: app/src/main/java/org/kodejava/tasknotes/model/Task.kt

package org.kodejava.tasknotes.model

data class Task(
    val id: Long,
    val title: String,
    val isCompleted: Boolean = false
)

A model describes information that the app works with. Here, each task has three properties:

Property Type Purpose
id Long Identifies the task even when its title changes
title String Holds the text shown to the user
isCompleted Boolean Records whether the task is done

The colon introduces a type. Boolean has two values: true and false. The default value means a new task starts incomplete unless you supply another value.

String does not accept null. It still accepts empty text such as ""; non-null types do not replace input validation. You will add form validation in a later article.

The data keyword asks Kotlin to generate useful operations such as equality checks, readable text output, and copying. Keep the properties in the primary constructor so those generated operations include them. See the official data class documentation.

2. Understand val and named arguments

This is an example of constructing a task; you do not need to add it to a file yet:

val task = Task(id = 1L, title = "Learn Kotlin basics")

val declares a reference that cannot be reassigned. The model also uses val properties, so you cannot assign a new title directly to an existing task.

1L is a Long literal. Named arguments such as title = ... make constructor calls easier to read. Since we omitted isCompleted, its value is false.

Kotlin also has var for variables that can be reassigned. We use val here to make changes explicit through new objects.

3. Prepare reusable sample data

Create a data package and add the following file:

File: app/src/main/java/org/kodejava/tasknotes/data/SampleTasks.kt

package org.kodejava.tasknotes.data

import org.kodejava.tasknotes.model.Task

fun sampleTasks(): List<Task> = listOf(
    Task(id = 1L, title = "Learn Kotlin basics"),
    Task(id = 2L, title = "Create the Task model", isCompleted = true),
    Task(id = 3L, title = "Build the task list")
)

fun declares a function. This function takes no arguments and returns a List<Task>, meaning a list whose elements are tasks. The = introduces a function with a single expression as its body.

listOf() creates the sample list. List exposes read-only operations: callers can inspect its elements but cannot call add() through that interface. A read-only interface is not a general guarantee that an underlying collection can never change. Our sample contains tasks with read-only properties and exposes no mutation operations.

The sample IDs are distinct and remain the same each time this function is called. They are manually assigned tutorial values; the function does not generate IDs for future user-created tasks. A title is not an ID because two tasks may have the same title.

Reference: Kotlin collections overview.

4. Display a task on the existing screen

In MainActivity.kt, add this import alongside the existing imports:

import org.kodejava.tasknotes.data.sampleTasks

Replace only the existing TaskNotesScreen() function with the code below. Keep MainActivity, its Scaffold and innerPadding, all existing Compose imports, and TaskNotesScreenPreview() from article 1.

File: app/src/main/java/org/kodejava/tasknotes/MainActivity.kt

@Composable
private fun TaskNotesScreen(modifier: Modifier = Modifier) {
    val tasks = sampleTasks()
    val task = tasks.first()
    val status = if (task.isCompleted) "Completed" else "Not completed"

    Column(
        modifier = modifier.fillMaxSize().padding(24.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Text(
            text = "Task Notes",
            style = MaterialTheme.typography.headlineMedium
        )
        Text(
            text = task.title,
            style = MaterialTheme.typography.bodyLarge
        )
        Text(text = "Status: $status")
        Text(text = "Sample tasks: ${tasks.size}")
    }
}

Kotlin infers the types of tasks, task, and status from their values. first() reads the first element. It is safe here because our sample function always returns three tasks; it would throw an exception for an empty list.

An if expression produces the status text. String templates insert values into text: $status inserts a variable, while ${tasks.size} evaluates an expression.

This screen only reads fixed sample data. Calling sampleTasks() during composition is acceptable for this tiny example; it is not a strategy for loading database data. Interactive state and its ownership come later in the series.

5. Create an updated task with copy()

To try a completed version, replace this line inside TaskNotesScreen():

val task = tasks.first()

with:

val original = tasks.first()
val task = original.copy(isCompleted = true)

The copied task keeps the original ID and title but has a new completion value. The original task and the task stored in the sample list remain incomplete. Copying an object does not replace an element in a list.

copy() is shallow: nested objects would still be shared. This model contains only a number, text, and a Boolean, so no mutable nested collection is involved.

After checking the result, restore val task = tasks.first() so your project matches the starting point for article 3.

6. Verify the result

  1. Sync the project if Android Studio requests it, then run the app on the emulator or phone used in article 1.
  2. Check that the screen shows the following text:
Task Notes
Learn Kotlin basics
Status: Not completed
Sample tasks: 3
  1. Refresh the existing Compose preview. It should show the same sample content.
  2. Try the copy() change from step 5. The status should become Completed, with the same title and sample count.
  3. Restore the original line and run again.

If Task or sampleTasks is unresolved, check the file package declarations and imports. If the compiler reports a type mismatch for an ID, use a Long literal such as 1L. If the preview cannot load, resolve build errors before refreshing it.

These are verification steps for your project. This draft’s Android build and device behavior have not been executed in an Android SDK environment.

Practice

  • Add a fourth sample task with ID 4L. Verify that the count becomes 4.
  • Display tasks[1] instead of the first task. The second task should show Completed. List indexes start at zero.
  • Use copy(title = "Review Kotlin basics") on the first task and observe that the original sample title stays unchanged.

Restore the three original samples and tasks.first() before continuing to the next article.

Gradle dependencies and compatibility

No additional Gradle dependencies are required. The model and sample function use the Kotlin standard library supplied by the existing Kotlin Android project. The screen reuses the Compose dependencies configured in article 1.

Keep the existing plugin and dependency versions in build.gradle.kts, app/build.gradle.kts, and gradle/libs.versions.toml if present. This lesson introduces no version-specific library API and does not require a Kotlin, Android Gradle Plugin, or Compose upgrade. Official Compose setup guidance remains the reference for project configuration.

Next in the series

In article 3, How Do I Display Tasks in a LazyColumn with Jetpack Compose?, you will reuse Task and sampleTasks() to render the task list.

How do I build my first Android app with Kotlin and Jetpack Compose?

Android Programming Essentials

In this first article of the Android with Kotlin and Jetpack Compose series, you will create Task Notes, a small app for keeping track of daily tasks. Today you will run the starter project and build the screen users see when their task list is empty. You will reuse this project throughout the series, all the way to preparing a release for Google Play.

Kotlin is the language you will use to write the app. Jetpack Compose is the toolkit you will use to describe what appears on the screen. For example, a Compose Text() call adds text to your interface.

1. Install Android Studio

Download the stable version of Android Studio and complete its setup wizard. Let it download the Android SDK and the recommended components. The first setup and build need an internet connection.

You can run the app on an Android emulator or on an Android phone. The emulator is a virtual Android device that runs on your computer.

2. Create the Task Notes project

  1. Select New Project from the welcome screen. If a project is already open, choose File > New > New Project.
  2. Under the phone and tablet templates, choose Empty Activity and click Next.
  3. Enter the following values and click Finish.
Setting Value
Name Task Notes
Package name org.kodejava.tasknotes
Minimum SDK API 24 (Android 7.0) for this tutorial
Build configuration language Kotlin DSL, if the wizard offers a choice

Use a package name under your own namespace if you plan to publish your own version. Android Studio normally uses the package name you enter here as the initial application ID. The minimum SDK determines the oldest Android version on which the app can be installed.

Wait for Gradle sync to finish. Gradle reads the project’s build configuration and downloads the libraries it needs. When the editor opens, find MainActivity.kt in the app module. With the sample package name, its path is app/src/main/java/org/kodejava/tasknotes/MainActivity.kt.

Reference: Create a project with Compose.

3. Run the generated app

To use an emulator, open Tools > Device Manager, create a virtual phone, and select a system image with API 24 or higher. Download the image if prompted. Select the virtual device in the toolbar and click Run.

To use a phone, enable Developer options and USB debugging, connect it with a USB data cable, and accept the debugging prompt on the phone. Select the phone in Android Studio and click Run.

Android Studio builds and installs the app on the selected device. Once the template screen opens, you can move on to editing it.

References: Run apps on the Android Emulator and Run apps on a hardware device.

4. Build the empty task screen

Replace the contents of MainActivity.kt with the following code. If you chose a different package name, keep your original package line and use the theme import and function name from your generated activity.

package org.kodejava.tasknotes

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import org.kodejava.tasknotes.ui.theme.TaskNotesTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        setContent {
            TaskNotesTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    TaskNotesScreen(modifier = Modifier.padding(innerPadding))
                }
            }
        }
    }
}

@Composable
private fun TaskNotesScreen(modifier: Modifier = Modifier) {
    Column(
        modifier = modifier.fillMaxSize().padding(24.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Text(
            text = "Task Notes",
            style = MaterialTheme.typography.headlineMedium
        )
        Text(
            text = "No tasks yet.",
            style = MaterialTheme.typography.bodyLarge
        )
    }
}

@Preview(showBackground = true)
@Composable
private fun TaskNotesScreenPreview() {
    TaskNotesTheme {
        TaskNotesScreen()
    }
}

When Android creates MainActivity, it calls onCreate(). Inside that method, setContent { ... } supplies the activity’s Compose UI, and TaskNotesTheme provides the app’s colors and text styles.

@Composable marks a function that can describe UI using other composable functions. Here, TaskNotesScreen() uses a Column to stack two Text() elements vertically. The 8.dp value adds space between them. Android uses density-independent pixels, or dp, to keep layout sizes consistent across screens with different pixel densities.

The app draws edge to edge. Passing innerPadding from Scaffold to the screen keeps the text clear of the system bars. The screen adds another 24.dp of padding for its own layout.

5. Check the result

Click Run again. You should see Task Notes near the top of the screen, with No tasks yet. on the line below. To inspect the layout in Android Studio, open the Split or Design view and build or refresh the preview if prompted. The @Preview function renders the screen in the editor.

If the theme import is unresolved, open the generated ui/theme/Theme.kt and check its package and theme function name. If Compose imports are unresolved, check that you selected Empty Activity and that Gradle sync completed successfully.

Practice

Change the message to Your task list is empty. and increase the space between the title and the message from 8.dp to 16.dp. Check the preview, then run the app to see the same changes on your device.

Gradle dependencies

The Empty Activity template sets up the Compose build configuration and dependencies for this example. Keep the generated entries in app/build.gradle.kts and, if the project uses one, gradle/libs.versions.toml. The code uses Activity Compose, Compose Material 3, and Compose UI Tooling Preview. This article requires no additional dependencies.

Next in the series

In the next article, How Do I Use Kotlin to Model Tasks in an Android App?, you will create a Kotlin Task data class with an ID, a title, and a completion flag. You will use that model to create the sample tasks for the list screen.