RecyclerView中的滚动条颜色

Yas*_*ass 26 android android-scrollbar android-recyclerview

如何在recyclerView中更改滚动条的颜色?

我有滚动条,但我想改变它的颜色.我的recyclerView是这样的:

 <android.support.v7.widget.RecyclerView
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:id="@+id/recyclerView"
   android:layout_below="@id/my_toolbar"
   android:layout_above="@+id/progressBar"
   android:scrollbars="vertical"
   />
Run Code Online (Sandbox Code Playgroud)

Nar*_*esh 50

您可以通过在Recyclerview中包含以下代码行来完成此操作

android:scrollbarThumbVertical="@drawable/yoursdrawablefile

我案例中的drawable文件是:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient android:startColor="#000" android:endColor="#000"
        android:angle="45"/>
    <corners android:radius="6dp" />
</shape>
Run Code Online (Sandbox Code Playgroud)


小智 15

如果您想进一步设置滚动条的样式,请在drawable文件夹中创建两个可绘制的资源文件,如1. scrollbar_track和2. scrollbar_thumb

scrollbar_track.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <gradient
        android:angle="0"
        android:endColor="#9BA3C5"
        android:startColor="#8388A4" />
        <corners android:radius="6dp" />
</shape>
Run Code Online (Sandbox Code Playgroud)

scrollbar_thumb.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <gradient
        android:angle="0"
        android:endColor="#b20111"
        android:startColor="#cf1d2d" />

    <corners android:radius="6dp" />

</shape> 
Run Code Online (Sandbox Code Playgroud)

现在,在文件中创建一个名为scrollbar_style的样式styles.xml:

<style name="scrollbar_style">
    <item name="android:scrollbarAlwaysDrawVerticalTrack">true</item>
    <item name="android:scrollbarStyle">outsideOverlay</item>
    <item name="android:scrollbars">vertical</item>
    <item name="android:fadeScrollbars">true</item>
    <item name="android:scrollbarThumbVertical">@drawable/scrollbar_thumb</item>
    <item name="android:scrollbarTrackVertical">@drawable/scrollbar_track</item>
    <item name="android:scrollbarSize">8dp</item>
    <item name="android:scrollbarFadeDuration">800</item>
    <item name="android:scrollbarDefaultDelayBeforeFade">500</item>
 </style>
Run Code Online (Sandbox Code Playgroud)

最后,要将此样式应用于recyclerview中的滚动条,请添加
style="@style/scrollbar_style"
到recyclerview.

在你的情况下:

<android.support.v7.widget.RecyclerView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:id="@+id/recyclerView"
  style="@style/scrollbar_style"
  android:layout_below="@id/my_toolbar"
  android:layout_above="@+id/progressBar"
  android:scrollbars="vertical"
 />
Run Code Online (Sandbox Code Playgroud)

  • 感谢 kaaloraat,它也可以工作,但上面的解决方案更适合初学者。 (2认同)