Android Compose – Display List of Items
To display a List of items in Android Compose from a Kotlin List, we may use a Column composable. Inside Column we iterate over items of the list, and return a composable for each item.
The following code snippet shows how to achieve the above solution.
Column { myList.forEach { item -> ItemRow(item) } }
Example
In this example, we display a list of students along with their credits.
- To store the details of each student, we use the data class
Student
. And initialized thestudents
list object with some dummy values. - Inside the composable
StudentList
, we have a Column in which we iterate over thestudents
list usingList.forEach{}
. The Column is set to scroll vertically usingmodifier
. - For each student, we return a
StudentRow
composable. InsideStudentRow
we are using aCard
to display the student details.
Create a Project in Android Studio with Empty Compose Activity template, and modify MainActivity.kt file as shown in the following.
MainActivity.kt
package com.example.myapplication import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.Card import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.myapplication.ui.theme.MyApplicationTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyApplicationTheme { Surface(color = MaterialTheme.colors.background) { StudentList(students) } } } } } data class Student(val name: String, val credits: Int) val students = listOf( Student("Student 1", 125), Student("Student 2", 75), Student("Student 3", 15), Student("Student 4", 87), Student("Student 5", 22), Student("Student 6", 96), ) @Composable fun StudentList(students: List<Student>) { Column(modifier = Modifier.verticalScroll(rememberScrollState())) { students.forEach { student -> StudentRow(student) } } } @Composable fun StudentRow(student: Student) { Card(modifier = Modifier .padding(all = 10.dp) .fillMaxWidth()) { Column(modifier = Modifier.padding(all = 10.dp)) { Text(student.name, fontSize = 25.sp, fontWeight = FontWeight.W700, modifier = Modifier.padding(10.dp)) Text(student.credits.toString(), color = Color.Gray, modifier = Modifier.padding(10.dp)) } } }
Screenshot
ADVERTISEMENT
Conclusion
In this Android Jetpack Compose Tutorial, we learned how to display items from a Kotlin List as a list of items in Android UI.