Search code examples
androidandroid-preferencesandroid-theme

selecting the color of preferences


Setting the theme, but whenever the color has been set the text color doesn't change on the dynamically made preferences.

<style name="PreferenceScreen" parent="AppTheme">
        <item name="android:color">@android:color/black</item>
        <item name="android:textColor">@android:color/black</item>
        <item name="android:textColorSecondary">@android:color/black</item>
        <item name="android:textColorTertiary">@android:color/black</item>
</style>

This is how the preferences are added:

Vector<String> categories = getCategories();

//Add all the categories to the preference
PreferenceCategory cat = (PreferenceCategory) findPreference("category_key");

for (final String categoryTitle : categories){
    final Preference pref = new Preference(getActivity().getApplicationContext());

    pref.setTitle(categoryTitle);
    pref.setWidgetLayoutResource(R.layout.list_black_text);
    cat.addPreference(pref);
}

Solution

  • Use pref.setLayoutResource(R.layout.list_item) instead of pref.setWidgetLayoutResource().

    You can define colors and styles in the above mentioned layout/list_item.xml, which should be something like:

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:clipToPadding="false"
        >
    
       <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingTop="16dp"
            android:paddingBottom="16dp">
    
            <TextView android:id="@+android:id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:singleLine="true"
                />
            <TextView android:id="@+android:id/summary"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@android:id/title"
                android:layout_alignLeft="@android:id/title"
                android:maxLines="10" />
        </RelativeLayout>
        <LinearLayout android:id="@+android:id/widget_frame"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="end|center_vertical"
            android:paddingLeft="16dp"
            />
    </LinearLayout>
    
    • @+android:id/title will be filled with your title;
    • @+android:id/summary with your summary;
    • @+android:id/widget_frame with anything you set up using pref.setWidgetLayoutResource() (may it be a CheckBox, or a Switch, or whatever).

    Just add XML attributes to change text color where needed.