edJoe
edJoe

Reputation: 23

How to check if the items in LazyColumn is too few for the height of the screen?

Since there is no scrollbar for LazyColumn, I tried this solution.

Is there a way for me to check if items are too few for the list to scroll because the scrollbar is still visible and I want to hide it if possible?

Upvotes: 2

Views: 1884

Answers (1)

Phil Dukhov
Phil Dukhov

Reputation: 88082

In such cases you should use the lazy list state: it contains information about the visible elements, you need to check that all of them are fully visible.

When you need to read any state continuously and produce some value depending on this state, you should use derivedStateOf to prevent redundant recompositions.

val state = rememberLazyListState()
val canBeScrolled by remember {
    derivedStateOf {
        val layoutInfo = state.layoutInfo
        val visibleItemsInfo = layoutInfo.visibleItemsInfo
        if (layoutInfo.totalItemsCount == 0) {
            false
        } else {
            val firstVisibleItem = visibleItemsInfo.first()
            val lastVisibleItem = visibleItemsInfo.last()
            
            val viewportHeight = layoutInfo.viewportEndOffset + layoutInfo.viewportStartOffset)

            !(firstVisibleItem.index == 0 &&
                    firstVisibleItem.offset == 0 &&
                    lastVisibleItem.index + 1 == layoutInfo.totalItemsCount &&
                    lastVisibleItem.offset + lastVisibleItem.size <= viewportHeight)
        }
    }
}
LazyColumn(state = state) {
    // ...
}

Upvotes: 3

Related Questions