如何为Android SwitchPreference添加背景颜色?

3
我正在使用PreferenceFragment来填充一个只有一个SwitchPreference的xml文件。如何使该偏好设置的背景颜色(包括SwitchPreference的标题)与下面的图像匹配?我尝试设置背景,但只能设置开关图标的背景颜色。

enter image description here


https://dev59.com/zWEi5IYBdhLWcg3wfsQj#21854548 - AskNilesh
我想要改变整个背景,包括文字后面的颜色。 - Alex Wilson
2个回答

1

styles.xml(将此样式制作在位于值文件夹中的style.xml文件中)

<resources>

<style name="SwitchTheme" parent="Theme.AppCompat.Light">
    <!-- switch on thumb & track color -->
    <item name="colorControlActivated">#02c754</item>

    <!-- switch off thumb color -->
    <item name="colorSwitchThumbNormal">#f1f1f1</item>

    <!-- switch off track color -->
    <item name="android:colorForeground">#42221f1f</item>
</style>

</resources>

your_layout_activity.xml

<android.support.v7.widget.SwitchCompat
    android:id="@+id/switch_on_off"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_gravity="center"
    android:checked="true"
    android:gravity="center"
    android:paddingLeft="30dp"
    android:theme="@style/SwitchTheme"
    app:switchMinWidth="55dp"/>

这个源代码对我有用。尝试一下,你会理解的。

0

我已经使用这种风格完成了这个任务。

Style.xml

<style name="SwitchTheme" parent="Theme.AppCompat.Light">
    <item name="colorControlActivated">@color/yourcolor</item>
</style>

在布局中

<android.support.v7.widget.SwitchCompat
    android:id="@+id/switch_on_off"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_gravity="center"
    android:checked="false"
    android:gravity="center"
    android:paddingLeft="@dimen/padding"
    android:paddingRight="@dimen/padding"
    app:switchMinWidth="@dimen/switch_size"
    app:theme="@style/SwitchTheme" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接