In this article, we’ll demonstrate how to incorporate the ScrollToTop feature, a widely-used functionality in Android, into a Jetpack Compose app.
Pre-requisites- Kotlin, Jetpack Compose, LazyLists
Output:
Creating:
In my actual project, I was using “LazyVerticalStaggeredGrid”, but most probably you might be using a “LazyColumn”. Don’t worry there is no difference in the implementation of the feature, just follow these steps:
The most important thing for us is the State of our List.
val listState = rememberLazyStaggeredGridState()
As I said, I was using Staggered Grid so I had to use this, but If you are using a LazyColumn, then use- rememberLazyListState()
LazyVerticalStaggeredGrid(
state = listState,//This is the main part [SAME FOR LAZYCOLUMN]
modifier = Modifier.padding(start = 10.dp, end = 10.dp, top = 5.dp),
columns = cellConfiguration,
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp)
)
And that’s it!
Now, your list state will be observed in that “listState” variable and we just have to use this to write our own condition for when we have to show our ScrollToTop icon.
For my case, I want to show if when the user had scrolled down to 10 or more items. So, we can check this condition by using our list state.
if(listState.firstVisibleItemIndex > 10){
//Create the icon of your choice
Icon(
modifier = Modifier
.padding(15.dp)
.clip(RoundedCornerShape(100.dp))
.size(50.dp)
.background(Color.Cyan)
.clickable {
coroutineScope.launch {
listState.animateScrollToItem(index = 0)
}
},
imageVector = Icons.Default.KeyboardArrowUp,
contentDescription = "Up"
)
}
Now, an Icon will automatically popup when 10 items are scrolled in your list.
Remember to add this in the same composable function, where you are getting the listState & creating your LazyList.
For some extra features, you can add here AnimatedVisibility instead of writing here a conditional statement.
//This is inside a Box compose,that's why here we have to specify full path
androidx.compose.animation.AnimatedVisibility(
modifier = Modifier.align(Alignment.BottomEnd),
visible = listState.firstVisibleItemIndex > 10,
enter = scaleIn() + expandVertically(expandFrom = Alignment.CenterVertically),
exit = scaleOut() + shrinkVertically(shrinkTowards = Alignment.CenterVertically)
) {
//Use same Icon here...
}
Now, we are done here. Enjoy your cool feature and give your user a great experience.
I hope you found this helpful. If yes, then do FOLLOW me for more Android-related content.
#androidWithSagar #android #androiddevelopment #development #compose #kotlin