Jetpack Compose 滚动条 [英] Jetpack Compose Scrollbars

查看:258
本文介绍了Jetpack Compose 滚动条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法添加滚动条来添加LazyColumn(ScrollableColumn 已弃用).Javadoc 没有提到有关 Jetpack Compose 中滚动条的任何内容.

Is there any way to add Scrollbars to add LazyColumn (ScrollableColumn is deprecated). The Javadoc doesn't mention anything about Scrollbars in Jetpack Compose.

澄清一下,这是我想要实现的设计:

Just to clarify, this is the design I want to implement:

现在还可以在 Jetpack Compose 中做到这一点吗?或者不支持滚动条?

Is it even possible to do that in Jetpack Compose yet? Or there are no support for Scrollbars?

推荐答案

现在实际上是可能的(他们已经在 LazyListState 中添加了更多的东西)而且很容易做到.这是一个非常原始的滚动条(始终可见/无法拖动等),它使用项目索引来确定拇指位置,因此在只有少数项目的列表中滚动时它可能看起来不太好:

It's actually possible now (they've added more stuff into LazyListState) and it's pretty easy to do. This is a pretty primitive scrollbar (always visible/can't drag/etc) and it uses item indexes to figure out thumb position so it may not look good when scrolling in lists with only few items:

  @Composable
  fun Modifier.simpleVerticalScrollbar(
    state: LazyListState,
    width: Dp = 8.dp
  ): Modifier {
    val targetAlpha = if (state.isScrollInProgress) 1f else 0f
    val duration = if (state.isScrollInProgress) 150 else 500

    val alpha by animateFloatAsState(
      targetValue = targetAlpha,
      animationSpec = tween(durationMillis = duration)
    )

    return drawWithContent {
      drawContent()

      val firstVisibleElementIndex = state.layoutInfo.visibleItemsInfo.firstOrNull()?.index
      val needDrawScrollbar = state.isScrollInProgress || alpha > 0.0f

      // Draw scrollbar if scrolling or if the animation is still running and lazy column has content
      if (needDrawScrollbar && firstVisibleElementIndex != null) {
        val elementHeight = this.size.height / state.layoutInfo.totalItemsCount
        val scrollbarOffsetY = firstVisibleElementIndex * elementHeight
        val scrollbarHeight = state.layoutInfo.visibleItemsInfo.size * elementHeight

        drawRect(
          color = Color.Red,
          topLeft = Offset(this.size.width - width.toPx(), scrollbarOffsetY),
          size = Size(width.toPx(), scrollbarHeight),
          alpha = alpha
        )
      }
    }
  }

更新:我已经更新了代码.我已经弄清楚如何在 LazyColumn 滚动时显示/隐藏滚动条 + 添加淡入/淡出动画.我还将 drawBehind() 更改为 drawWithContent() 因为前者在内容后面绘制,因此在某些情况下它可能会绘制在滚动条的顶部,这很可能是不可取的.

UPD: I've updated the code. I've figured out how to show/hide scrollbar when LazyColumn is being scrolled or not + added fade in/out animation. I also changed drawBehind() to drawWithContent() because the former draws behind the content so it may probably draw on top of the scrollbar in some cases which is most likely not desireable.

这篇关于Jetpack Compose 滚动条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆