How to display a list of items in Jetpack Compose In late July 2021, the Google team announced Jetpack Compose. Jetpack compose makes it faster and easier to build native Android apps, unlike the existing approach where you have an XML file, activity, fragments, etc. Some of the advantages Jetpack compose offers include automatic UI updates when app state changes and native access to all existing Android code. You can see more in the announcement link Jetpack Compose Announcement. This guide will leverage Jetpack Compose to build an app that displays a list of items.
Previously on native Android before Jetpack Compose, this will be done with a recyclerview or listview. You will also need adapters to manage how the data is being displayed to the user. Jetpack Compose makes this process easier and faster.
Create a new Android Studio Project.
The first thing we do after opening Android Studio is to click on File -> New -> New Project. Then click on the Empty Compose Activity template. Click Finish when you are done.
Implement the list in MainActivity.
In MainActivity onCreate method we modify the setContent section by adding a Surface container
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ListAppComposeTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
DisplayBrands()
}
}
}
}
Creating Composable with a title and a list
You can create a UI component in Jetpack Compose by creating composable functions. This is done by adding the @Composable annotation to a function. In the code snippet below we create a DisplayBrands() composable method. Which contains a page title and a list. A list is done using the LazyColumn component.
@Composable
fun DisplayBrands() {
// List of strings with shoe brands
val itemsToShow = listOf(
"Addidas", "Nike", "Louis Vuitton", "Reebok", "Under Amour", "Lacoste", "New Balance"
)
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.padding(18.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
PageTitle("Popular Shoe Brands")
// Use lazy column to show a listview listview.
LazyColumn {
items(itemsToShow) { brand ->
Card(
shape = RoundedCornerShape(8.dp),
backgroundColor = MaterialTheme.colors.surface,
modifier = Modifier
.padding(10.dp)
.fillMaxWidth()
.fillMaxHeight(), elevation = 10.dp
) {
Text(brand, modifier = Modifier.padding(15.dp), textAlign = TextAlign.Center)
}
}
}
}
}
In conclusion, we can see that creating a list in Jetpack Compose is straightforward. All we just need to do is to use the LazyColumn component. Declare the object for the list item as well as the item component like the Card component used in the code above and wrap all of them in a composable function. You can see the full code here: Sample Code