android 有人知道如何改变宽度/长度的回收器视图滚动条像这样?

mspsb9vt  于 2023-03-11  发布在  Android
关注(0)|答案(1)|浏览(147)

请参见蓝色矩形中的滚动条:

这是我的代码,我想改变滚动条的长度:

<androidx.recyclerview.widget.RecyclerView
                android:id="@+id/recyclerViewTeaser"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:scrollbars="horizontal"
                android:fadeScrollbars="false"
                android:scrollbarThumbHorizontal="@color/orange_color_picker"
                android:scrollbarTrackHorizontal="@color/gray"
                app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
jbose2ul

jbose2ul1#

你可以创建自己的滚动条,并将其与回收视图绑定。以下是回收视图处理上述滚动条的扩展方法

fun RecyclerView.handleScroll(itemScrollerBinding: ItemScrollerBinding) {
    post {
        val parentWidth = itemScrollerBinding.parent.width
        val layoutParams = itemScrollerBinding.progress.layoutParams
        val initialX = itemScrollerBinding.progress.x
        layoutManager?.let {
            val totalWidth = this.computeHorizontalScrollRange()
            val visibleWidth = this.computeHorizontalScrollExtent()
            val percent =
                visibleWidth.toFloat() / totalWidth.toFloat()
            layoutParams.width = (parentWidth * percent).toInt()
            itemScrollerBinding.progress.layoutParams = layoutParams
            addOnScrollListener(object :
                RecyclerView.OnScrollListener() {

                override fun onScrolled(
                    recyclerView: RecyclerView,
                    dx: Int,
                    dy: Int,
                ) {
                    super.onScrolled(recyclerView, dx, dy)
                    val scrolledWidth =
                        this@handleScroll.computeHorizontalScrollOffset()
                    val updatedVisibleWidthRecyclerView =
                        visibleWidth + scrolledWidth
                    val scrolledWidthScroller =
                        ((parentWidth.toFloat() / totalWidth) * scrolledWidth)
                    itemScrollerBinding.progress.x =
                        initialX + scrolledWidthScroller
                }
            })
        }
    }
}

以下是ItemScrollerBinding的xml代码

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parent"
    android:layout_width="@dimen/size_48"
    android:layout_height="@dimen/size_6"
    android:background="@drawable/bg_scroller_background">

    <LinearLayout
        android:id="@+id/progress"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:background="@drawable/bg_scroller"
        android:orientation="horizontal" />

</FrameLayout>

您可以将其放置在回收器视图下方并使其居中。

相关问题