Build Layouts with Jetpack Compose

Sep 10 2024 · Kotlin 1.9, Android 14, Android Studio Iguana | 2023.2

Lesson 02: Leverage Lists

Demo

Episode complete

Play next episode

Next
Transcript

Open the Starter project in the 02-leverage-lists directory of the m3-ljp-materials repo in Android Studio Hedgehog or later.

Build and run the project.

This is the same app you’ve worked on so far.

In the last lesson, you made the GitHubRepoList composable scrollable.

As you’ve learned in this lesson, using the regular layout composables to render large, dynamic data sets can be inefficient.

To fix this, you’ll swap them out with their lazy variants, which are far more efficient because they don’t render the items that aren’t in the screen viewport.

In the GitHubRepoList, swap out the Column for a LazyColumn as follows:


@Composable
fun GitHubRepoList() {
  val viewModel: MainViewModel = viewModel()
  val state by viewModel.state.observeAsState()
  LazyColumn(
    modifier = Modifier.fillMaxSize(),
    contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
    verticalArrangement = Arrangement.spacedBy(16.dp),
  ) {
      state?.forEach { repo ->
        GitHubRepoCard(repo)
        Spacer(modifier = Modifier.height(16.dp))
      }
  }
}

Here, you:

  • Swapped out the Column for a LazyColumn.
  • Specified a contentPadding that adds the specified padding values to the entire list.
  • Specified a verticalArrangement such that places items 16dp apart.

Next, swap out the forEach loop for the items receiver as follows:

items(state ?: emptyList()) { repo ->
  GitHubRepoCard(repo)
}

If Android Studio shows an error, you might need to import the items method:

import androidx.compose.foundation.lazy.items

In the items receiver, you passed in the state object. Because the state is a nullable property, you used the elvis operator to fall back to an empty list when the value is null.

The items receiver composes a GitHubRepoCard for each repo.

Build and run the app. Visually, nothing has changed; you still have a list of items that you can scroll through. But behind the scenes, this implementation runs far more efficiently than before, because the runtime renders only items that can fit in the screen’s viewport. It composes new items only when you scroll, preventing overdraw.

That concludes this demo. Continue on for the lesson a summary.

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion