1

我正在使用PreferenceFragment通过一个SwitchPreference对一个xml文件进行充气。我如何制作该首选项的背景颜色,包括SwitchPreference的标题以匹配下面的图像。我已经尝试设置背景,但我只能设置开关图标的背景颜色。如何将背景颜色添加到Android SwitchPreference?

enter image description here

+0

https://stackoverflow.com/questions/21235829/custom-switchpreference-in-android/21854548 –

+0

我期待改变整个背景,包括文字背后的颜色 –

回答

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" /> 
0

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"/> 

这个源为我工作。试试这个,你会明白