Search code examples
androidscrollbarandroid-jetpack-compose

How to make a scrollbar View with Jetpack Compose


I want something like this image. I tried many solutions but no result.

enter image description here


Solution

  • I use this code to show how much of the page has been scrolled

    BoxWithConstraints() {
                val scrollState = rememberScrollState()
                val viewMaxHeight = maxHeight.value
                val columnMaxScroll = scrollState.maxValue
                val scrollStateValue = scrollState.value
                val paddingSize = (scrollStateValue * viewMaxHeight) / columnMaxScroll
                val animation = animateDpAsState(targetValue = paddingSize.dp)
                val scrollBarHeight = viewMaxHeight / items
    
                Column(
                    Modifier
                        .verticalScroll(state = scrollState)
                        .fillMaxWidth(),
                    verticalArrangement = Arrangement.spacedBy(8.dp),
                ) {
                   if (scrollStateValue < columnMaxScroll) {
                    Box(
                        modifier = Modifier
                            .paddingFromBaseline(animation.value)
                            .padding(all = 4.dp)
                            .height(scrollBarHeight.dp)
                            .width(4.dp)
                            .background(
                                color = MaterialTheme.colors.primary.copy(alpha = ContentAlpha.disabled),
                                shape = MaterialTheme.shapes.medium
                            )
                            .align(Alignment.TopEnd),
                    ) {}
                }
          }
    }
    

    Result:

    1