Search code examples
androidandroid-preferencesandroid-stylesandroid-5.0-lollipop

'preferenceCategory' style background isn't working in Lollipop


I used to use the following style to set my preferenceCategory.
But as it looks, the background color isn't applied when running on Lollipop.

<style name="Theme.Preference.Category" parent="@android:attr/listSeparatorTextViewStyle">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textColor">@color/primary_light</item>
    <item name="android:background">@color/primary_dark</item>
    <item name="android:paddingTop">4dp</item>
    <item name="android:paddingBottom">4dp</item>
    <item name="android:paddingLeft">4dp</item>
</style>

And I set it : <item name="android:listSeparatorTextViewStyle">@style/Theme.Preference.Category</item> in my theme.

is the background attribute changed in Lollipop ?


Solution

  • Because of the way Preference is structured, you will need to create a layout with these properties and set the android:layout attribute in the style referenced by your themes's android:preferenceCategoryStyle.

    The example code below is suitable for Material. You will need to find appropriate substitutes if you're targeting Holo or AppCompat.

    res/values/themes.xml:

    <style name="MyAppTheme" parent="@android:style/Theme.Material.Light.DarkActionBar">
        ...
        <item name="android:preferenceCategoryStyle">@style/MyCategoryPreferenceStyle</item>
    </style>
    

    res/values/styles.xml

    <style name="MyCategoryPreferenceStyle" parent="@android:style/Preference.Material.Category">
        ...
        <item name="android:layout">@layout/my_category_preference</item>
    </style>
    

    You will apply whatever attributes you need in the following layout. You could also continue to use a style and specify a style attribute on the TextView element, but just make sure you're using a valid parent style.

    res/layout/my_category_preference.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dip"
        android:textAppearance="@android:style/TextAppearance.Material.Body2"
        android:textColor="?android:attr/colorAccent"
        android:paddingStart="?android:attr/listPreferredItemPaddingStart"
        android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
        android:paddingTop="16dip" />