daniyelp
daniyelp

Reputation: 1275

Jetpack Compose - Detect when LazyColumn's scroll position is at the first index

I want to have a Scroll back to top button for my LazyColumn. I successfully made the button work. But I want it to not be visible if I'm already at the top of the LazyColumn. How could I achieve this?

Upvotes: 9

Views: 16904

Answers (3)

Castaldi
Castaldi

Reputation: 701

to know if you are at the top most of the list use

val isOnTopOfList = lazyListState.firstVisibleItemIndex == 0 && lazyListState.firstVisibleItemScrollOffset == 0

Upvotes: 0

Johann
Johann

Reputation: 29885

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        startActivity(intent)

        setContent {
            val scrollState = rememberLazyListState()
            val coroutineScope = rememberCoroutineScope()

            Column(modifier = Modifier.fillMaxSize()) {
                if (scrollState.firstVisibleItemIndex > 0) {
                    Button(onClick = {
                        coroutineScope.launch {
                            scrollState.scrollToItem(0)
                        }
                    }, enabled = scrollState.firstVisibleItemIndex > 0) {
                        Text("Scroll to top")
                    }
                }

                LazyColumn(modifier = Modifier.fillMaxSize(), state = scrollState) {
                    items(MutableList(100) { it }) { i ->
                        Text(i.toString())
                    }
                }
            }
        }
    }
}

Upvotes: 3

Phil Dukhov
Phil Dukhov

Reputation: 88407

LazyColumn has state property, and if you pass your custom value instead of the default one, you can react on the state changes.

To prevent redundant recompositions, in such cases derivedStateOf should be used: it'll trigger recomposition only when the produced result, based on other state variables, is changed:

Box {
    val state = rememberLazyListState()
    LazyColumn(state = state) {
        // ...
    }
    val firstItemVisible by remember {
        derivedStateOf {
            state.firstVisibleItemIndex == 0
        }
    }
    if (!firstItemVisible) {
        Button(onClick = { /*TODO*/ }) {

        }
    }
}

Upvotes: 17

Related Questions