Android:RecyclerView中滚动条的轨迹比拇指细

问题描述

如何在不使用自定义scrollView的情况下将滚动条轨道设置为比RecyclerView中的拇指更细

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/rv"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:scrollbars="vertical"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:fadeScrollbars="false"
    android:scrollbarSize="4dp"
    android:scrollbarThumbVertical="@drawable/scroll_view_gradient"
    android:scrollbarTrackVertical="@color/scroll_bar_track"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

解决方法

Example of how it looks at the end 我是自己做的,它看起来很“不错”,并且表现得“有点不错”,但是有些事情没有经过足够的测试,至少应该有所帮助。也可以在this link上进行检查。另外,这首先只是视觉上的,如果要自定义拇指的长度,则需要创建自定义视图并操纵偏移量。由于它不是问题(和答案)的一部分,因此我没有编写它,如果有人需要它,可以在上面的链接中找到它。

底部,左侧,右侧和顶部是插图,您可以将它们视为填充,它们不会影响布局大小,但您应将轨道和拇指上的顶部和底部插图保持相同的尺寸(对于垂直recyclerviews,水平的应该使用left和right)。 还控制拇指和轨迹的厚度,笔划宽度放置透明像素,因此轨迹看起来比实际小。 @Razvan S.的荣誉 scrollbar_track.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:bottom="8dp"
        android:left="8dp"
        android:right="8dp"
        android:top="8dp">
        <shape>
            <solid android:color="@color/scroll_bar_color" />
            <stroke
                android:width="3dp"
                android:color="@android:color/transparent" />
            <size android:width="4dp"
                  android:height="4dp" />
        </shape>
    </item>
</layer-list>

这不需要width和height属性,因为recyclerview会自动计算长度,而磁道宽度会设置拇指宽度。 thumb_shape.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:bottom="8dp"
        android:left="8dp"
        android:right="8dp"
        android:top="8dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/scroll_bar_color" />
            <corners android:radius="4dp" />
        </shape>
    </item>
</layer-list>

styles.xml

<style name="scrollbar_style">
    <item name="android:scrollbarAlwaysDrawVerticalTrack">true</item>
    <item name="android:scrollbars">vertical</item>
    <item name="android:fadeScrollbars">false</item>
    <item name="android:scrollbarThumbVertical">@drawable/thumb_shape</item>
    <item name="android:scrollbarTrackVertical">@drawable/scrollbar_track</item>
</style>
您布局中的

recyclerview标记: style =“ @ style / scrollbar_style”

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    style="@style/scrollbar_style" />

现在是第二部分,如果要控制拇指的长度,则需要自己计算偏移量。为此,我创建了一个实现 ScrollingView 自定义RecyclerView ,并手动计算了所有内容。

希望这对您有所帮助,它为我完成了工作。

对于那些想知道的人,我使用了layer-list,因为它可以按我的意愿工作,如果我切换到其他东西,则我不会得到想要的行为。这可能有点瑕疵,并且可能会有更好的解决方案,但是我还是反复尝试,直到产生出可以使用的东西为止。