Bye đź‘‹ Recycler View Adapter

Andrea
2 min readSep 21, 2022

--

If you are native Android Developer, Recycler View is your must have item in every project. We all familiar with the old way of building Recycler View by setting the XML Layout, binding the layout and logic inside Fragment, and build special class for its Adapter.

However with the release of Jetpack Compose, all these codes will be replace with just a few line of code :

@Composable
fun PokemonView(data: List<Pokemon>) {
LazyColumn(
verticalArrangement = Arrangement.spacedBy(8.dp),
contentPadding = PaddingValues(8.dp)
) {
itemsIndexed(data) { index, pokemon ->
Row(
modifier = Modifier
.background(Color.Black)
.fillMaxWidth()
.padding(12.dp)
) {
Image(
painter = painterResource(android.R.drawable.star_big_off),
contentDescription = "avatar",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(48.dp)
.clip(CircleShape)
.border(2.dp, Color.Yellow, CircleShape)
)
Column(modifier = Modifier.padding(horizontal = 12.dp)) {
Text(
text = String.format("#%03d", index + 1),
fontSize = 16.sp,
color = Color.White
)
Text(text = pokemon.name ?: "", fontSize = 16.sp, color = Color.LightGray)
}
}
}
}
}

Above 33 lines codes has been replacing our XML Layout & RecyclerViewAdapter class, with the same view result.

Jetpack Compose is Android’s modern toolkit for building native UI. It simplifies and accelerates UI development on Android. Quickly bring your app to life with less code, powerful tools, and intuitive Kotlin APIs.

It also can be combined with your existing UI design implementation.

As per Android Developer documentation, a compatible view of Recycler View from Jetpack Compose is LazyList and LazyGrid. It can be used in Vertical or Horizontal scrolling manner, and has simpler code compare to RecyclerView Adapter.

Let’s say we want to make multiple type of items into our RecyclerView. I have written the old way of doing it before here.

LazyColumn {
// Add first type of item
item {
Image()
}

// Add another type of item
items(5) { index ->
Text(text = "Item: $index")
}

// Add another type of item
item {
Button()
}
}

We can also custom the layout of the items inside the same function

@Composable
fun PokeView(data: List<Pokemon>) {
LazyColumn() {
items(data) { pokemon ->
//custom item layout and engaged with data directly
Row
() {
Image(
painter = painterResource(R.drawable.avatar),
contentDescription = "avatar",
)
Column() {
Text(text = pokemon.index)
Text(text = pokemon.name)
}
}
}
}
}

It is a recommended action to migrate your project into Jetpack Compose gradually.

https://github.com/andrea-liu87/Ikigai/tree/compose_lazylist

--

--

Andrea
Andrea

Written by Andrea

Mother on daytime. Android Dev on nighttime. https://andrea-liu87.github.io | ♡ coffee https://ko-fi.com/snufflesrea

No responses yet