Home > Back-end >  Android Jetpack Compose Scroll to Top
Android Jetpack Compose Scroll to Top

Time:05-28

In Jetpack Compose, where is ScrollToTopButton coming from? It is mentioned in Google's documentation. Annoyingly, they neglect to mention the package. I have imports of foundation version 1.2.0-alpha08; also tried with 1.2.0-beta02 as well as ui and material (1.1.1). Not found. (yes did do an internet search on the term, came back empty handed).

implementation "androidx.compose.foundation:foundation:${version}"
implementation "androidx.compose.foundation:foundation-layout:${version}"
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"

    @Composable
    fun MessageList(messages: List<Message>) {
        val listState = rememberLazyListState()
        // Remember a CoroutineScope to be able to launch
        val coroutineScope = rememberCoroutineScope()
    
        LazyColumn(state = listState) {
            // ...
        }
    
        ScrollToTopButton(
            onClick = {
                coroutineScope.launch {
                    // Animate scroll to the first item
                    listState.animateScrollToItem(index = 0)
                }
            }
        )
    }

Google documentation

CodePudding user response:

It's not clear from the documentation but you actually have to make your own. For example you can use this:

    @Composable
fun ScrollToTopButton(onClick: () -> Unit) {
    Box(
        Modifier
            .fillMaxSize()
            .padding(bottom = 50.dp), Alignment.BottomCenter
    ) {
        Button(
            onClick = { onClick() }, modifier = Modifier
                .shadow(10.dp, shape = CircleShape)
                .clip(shape = CircleShape)
                .size(65.dp),
            colors = ButtonDefaults.buttonColors(
                backgroundColor = Color.White,
                contentColor = Color.Green
            )
        ) {
            Icon(Icons.Filled.KeyboardArrowUp, "arrow up")
        }
    }
}

And then:

val showButton = listState.firstVisibleItemIndex > 0
    AnimatedVisibility(
        visible = showButton,
        enter = fadeIn(),
        exit = fadeOut(),
    ) {
        ScrollToTopButton(onClick = {
            scope.launch {
                listState.animateScrollToItem(0)
            }
        })
    }
  • Related