Kotlin with Jetpack Compose -List View
--
A List View is a basic component that we need in mobile development. In order to create a list view that scroll vertically, we can use LazyColumn
with Jetpack compose. We can use a LazyRow
to create a horizontal item list view.
When displaying a large number of items with an unknown length, using Column or Row will cause performance issues.
Compose provides a set of components which only compose and lay out items which are visible in the component’s viewport. These components include LazyColumn and LazyRow.
Properties of a lazy column.
@Composable
fun LazyColumn(
modifier: Modifier = Modifier,
state: LazyListState = rememberLazyListState(),
contentPadding: PaddingValues = PaddingValues(0.dp),
reverseLayout: Boolean = false,
verticalArrangement: Arrangement.Vertical =
if (!reverseLayout) Arrangement.Top else Arrangement.Bottom,
horizontalAlignment: Alignment.Horizontal = Alignment.Start,
flingBehavior: FlingBehavior = ScrollableDefaults.flingBehavior(),
userScrollEnabled: Boolean = true,
content: LazyListScope.() -> Unit
) {
Lets see an example.
Creating a Data class and a list of data
data class ListItem(
val id: Int,
val title: String,
val subtitle: String,
val image: Int
)
val listItems = listOf(
ListItem(1, "Jane doe", "Subtitle for item 1", R.drawable.avatar),
ListItem(2, "Robert C. Williams", "Subtitle for item 2", R.drawable.avatar2),
ListItem(3, "Kendrick M. Valdez", "Subtitle for item 3", R.drawable.avatar3)
)
Creating a Single List Item view
You can see the list items that I wanted. Image avatar, Name, Another text under the name and an icon at the end of the list item. I wanted all these inside a card view.
So we need to add a Card
with a Row
inside to organize the item row. Inside the Row
we have to add an Image
with a circle shape, Column
and an IconButton
. We have to use the modifier
and style
params to give the look I wanted.
I added .weight(1f)
to the modifier of theColumn
in the middle to display the phone icon at the end of the row.
fun ListItem(item: ListItem) {
Card(
modifier =…