首页 > 解决方案 > 如何设置 android studio 材质滑块的样式

问题描述

如何设置滑块的样式,例如使用 xml 更改其轨道和拇指等的颜色?

滑块.xml:

    <com.google.android.material.slider.Slider
        android:id="@+id/settingsMission_changeShakeDif_slider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:stepSize="20.0"
        android:theme="@style/SliderTheme"
        android:valueFrom="0.0"
        android:valueTo="40.0"
        app:labelBehavior="gone" />

主题.xml

    <style name="SliderTheme" parent="Widget.MaterialComponents.Slider">
        <!-- Add attributes here -->

        <item name="trackColorActive">#238ae6</item>
        <item name="trackColorInactive">#a7bada</item>
        <item name="tickColor">#13161d</item>
        <item name="thumbColor">#238ae6</item>

    </style>

当我这样做时,我的滑块的颜色没有改变(它仍然是默认的紫色)

当我尝试运行应用程序并打开具有滑块的底部工作表对话框时,应用程序崩溃。我也收到此运行时错误:

原因:java.lang.IllegalArgumentException:此组件上的样式要求您的应用主题为 Theme.AppCompat(或后代)。

标签: javaandroid-studioslider

解决方案


发现这篇有用的文章解决了我的问题:

https://github.com/material-components/material-components-android/issues/1145

对代码所做的更改:

滑块.xml

    <com.google.android.material.slider.Slider
        android:id="@+id/settingsMission_changeShakeDif_slider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:stepSize="20.0"
        android:theme="@style/AppTheme"
        android:valueFrom="0.0"
        android:valueTo="40.0"
        app:labelBehavior="gone"
        app:thumbColor="#238ae6"
        app:tickColor="#13161d"
        app:trackColorActive="#238ae6"
        app:trackColorInactive="#a7bada" />


主题.xml

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">

推荐阅读