How to change text color of preference category in Android?
Asked Answered
E

14

47

The textColor attribute isn't working. Here's my XML:

<PreferenceCategory
        android:title="Title"
        android:textColor="#00FF00">

Any ideas?

Earsplitting answered 23/7, 2012 at 6:16 Comment(0)
T
58

use this customize PreferenceCategory class :

public class MyPreferenceCategory extends PreferenceCategory {
    public MyPreferenceCategory(Context context) {
        super(context);
    }

    public MyPreferenceCategory(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyPreferenceCategory(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onBindView(View view) {
        super.onBindView(view);
        TextView titleView = (TextView) view.findViewById(android.R.id.title);
        titleView.setTextColor(Color.RED);
    }
}

and add this at your Pref.xml file :

<ali.UI.Customize.MyPreferenceCategory android:title="@string/pref_server" />
Timeconsuming answered 23/7, 2012 at 6:19 Comment(4)
I found that findViewById() still didn't work in onBindView(). I did it in onCreateView() instead, which worked.Authoritative
titleView.setTextColor(Color.RED); throws NullPointerException. Any fix?Diaeresis
Note that one must replace ali.UI.Customize with the package name of your own MyPreferenceCategory.Matheny
Great thanks! This is the code for overriding the android.support.v7.preference.PreferenceViewHolder, in replacement of the method onBindView: @Override public final void onBindViewHolder(final PreferenceViewHolder vh) { super.onBindViewHolder(vh); TextView txt = (TextView) vh.findViewById(android.R.id.title); txt.setTextColor(Color.RED); }Nessie
C
50

An easy way to do this is to set the custom layout for the preferenceCategory here:

<PreferenceCategory
    android:layout="@layout/preferences_category"
    android:title="Privacy" >

Then set your code inside your preferences_category layout file:

<TextView
    android:id="@android:id/title"
    android:textColor="@color/deep_orange_500"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:textStyle="bold"
    android:textAllCaps="true"/>

Crossfade answered 9/1, 2016 at 18:16 Comment(4)
The best solution, because you have direct control of everything inside the textviewRevoice
I can't get the text from the Category-title to the layout-textView, it's simply a blank area. How do I add it?Gizela
The android:id="@android:id/title" part is necessary for the preference category text to be visible.Pitchblende
"The resource @layout/preferences_category is marked as private in androidx.preference:preference:1.2.0" is there a way around this?Capping
C
48

One solution is to make a theme for your PreferenceScreen. So in your themes.xml or styles.xml (better to put it in themes.xml) :

<style name="PreferenceScreen" parent="YourApplicationThemeOrNone">
    <item name="android:textColor">@color/yourCategoryTitleColor</item>
</style>

then in your AndroidManifest.xml :

<activity
      android:name="MyPreferenceActivity"
      ...
      android:theme="@style/PreferenceScreen" >
</activity>

It worked perfectly for me.

Crochet answered 23/7, 2012 at 7:29 Comment(4)
@Javi Same here, this answer allows you to dynamically change the theme details! :)Juice
Holy sh*t, how are all the other answers everywhere so complicated and long when you can make it so simple?? Thank you!Eichelberger
It worked perfectly but you need Add these lines to the Style <item name="android:textColorTertiary">@color/with</item> <item name="android:textColorSecondary">@color/with</item>Belfast
This still doesn't change the color of PreferenceCategory title (` <PreferenceCategory android:title="Settings">`)Omission
G
15

To change text color of preference category only set a theme to your PreferenceActivity in your Android Manifest and make sure that colorAccent item exists. This color is taken by your PreferenceCategory.

Germany answered 1/6, 2016 at 16:6 Comment(2)
This is the correct answer! Add <item name="colorAccent">@android:color/white</item> to the theme for your PreferenceActivity and the color of the checkboxes and titles will change to white.Vietnam
This is no longer true as of Android P and it's support libraries. They arbitrarily get set to grey. Will look at the source and figure out somethingTokenism
W
14

Actually just found out that preference category text using colorAccent.

If your app didn't using style of colorAccent, you can go to styles.xml and find
<item name="colorAccent">@color/colorPrimary</item>, and change the color as you want.

Waspish answered 7/11, 2017 at 15:56 Comment(2)
IMO, this is the correct answer as of Lollipop and material design. Reference - grepcode.com/file/repository.grepcode.com/java/ext/…Glottal
Thanks, this was actually my mistake.Crocus
I
8

Other way around will be mention the theme in your AppTheme, application level

    <style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
        .....//your other items
        <item name="preferenceTheme">@style/PrefTheme</item>
    </style>

    <style name="PrefTheme" parent="@style/PreferenceThemeOverlay">
        <item name="preferenceCategoryStyle">@style/CategoryStyle</item>
    </style>

    <style name="CategoryStyle" parent="Preference.Category">
        <item name="android:layout">@layout/pref_category_view</item>
    </style>

XML : pref_category_view

<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="@android:id/title"
          style="?android:attr/listSeparatorTextViewStyle"
          xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:textColor="@color/red"
          android:layout_height="wrap_content"
    />

For more customization visit v7 Preferences res

Important: I am using PreferenceFragmentCompat from lib v7 Preference.

Isadora answered 13/1, 2016 at 6:38 Comment(2)
This is the most correct answer to cover all API levels. Just setting colorAccent will not work for API <21. For the lazy like myself, there is an color defined in values '<color name="preference_fallback_accent_color">#ff80cbc4</color>' which one could override in their own colors.xml. Setting this along with 'colorAccent' should handle changing the text color on all APIs.Mcclintock
I didn't triy this but this will work probalbly and this is the best way I think.Lumberman
K
7

Using Material Theme, you just have to override the following property :

<style name="YourTheme" parent="@style/Theme.MaterialComponents">
    <item name="colorAccent">@color/your_custom_color</item>
</style>
Kehr answered 8/11, 2019 at 10:48 Comment(1)
This is so much easier! Why would I use a customized class to just set the category title color globally?Woothen
A
2
public class MyPreferenceCategory extends PreferenceCategory {

 public MyPreferenceCategory(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
  }
 public MyPreferenceCategory(Context context, AttributeSet attrs) {
    super(context, attrs);
  }
 public MyPreferenceCategory(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    // TODO Auto-generated constructor stub
  }

 @Override
 protected View onCreateView(ViewGroup parent) {
    // It's just a TextView!
 TextView categoryTitle =  (TextView)super.onCreateView(parent);
 categoryTitle.setTextColor(parent.getResources().getColor(R.color.orange));

    return categoryTitle;
  }
}

And in your prefs.xml:

<com.your.packagename.MyPreferenceCategory android:title="General">
.
.
.
</com.your.packagename.MyPreferenceCategory>

Or you can also use this answer

Astaire answered 26/1, 2015 at 17:34 Comment(2)
This worked perfectly for me with one modification. Instead of categoryTitle.setTextColor(parent.getResources().getColor(R.color.orange)); I had to use categoryTitle.setTextColor(Color.BLACK);Mcgray
This doesn't work for me. I get a ClassCastException, because my Category class is tried to be cast to a Preference instead of a PreferenceCategory. Any ideas why?Pitchblende
S
2

Define your own PreferenceTheme and override colors.

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="preferenceTheme">@style/AppTheme.PreferenceTheme</item>
</style>

<style name="AppTheme.PreferenceTheme" parent="PreferenceThemeOverlay.v14.Material">
    <item name="colorAccent">`#color_value`</item>
</style>
Sworn answered 5/9, 2018 at 12:48 Comment(0)
T
1

Inspired by @AliSh answer, but I needed to only change the colour of one Preference text item. So, for all the Kotlin guys out there:

class TextColorPreference : Preference {

    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    constructor(
        context: Context, attrs: AttributeSet,
        defStyle: Int
    ) : super(context, attrs, defStyle)

    override fun onBindViewHolder(holder: PreferenceViewHolder?) {
        super.onBindViewHolder(holder)

        context?.let {
            (holder?.findViewById(android.R.id.title) as? TextView)?.setTextColor(
                ContextCompat.getColor(
                    it,
                    R.color.colorPrimary
                )
            )
        }
    }
}

And then put it in your xml/prefs.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <this.should.be.your.package.TextColorPreference
        android:id="@+id/settings_logout"
        android:key="@string/prefs_key_logout"
        android:title="@string/settings_logout" />
</PreferenceScreen>
Transportation answered 25/9, 2019 at 16:6 Comment(0)
F
1

For androidx preference library you can extend PreferenceCategory or Preference class like this:

class DangerPreference(
    context: Context?,
    attrs: AttributeSet?,
): Preference(context, attrs) {

    override fun onBindViewHolder(holder: PreferenceViewHolder?) {
        super.onBindViewHolder(holder)
        holder?.itemView?.findViewById<TextView>(android.R.id.title)?.setTextColor(Color.RED)
    }
}

then use it normally in your PreferenceScreen:

<com.github.anastr.myscore.util.pref.DangerPreference
    app:key="deleteServerData"
    app:title="@string/delete_server_data"
    app:iconSpaceReserved="false" />
Fonda answered 6/3, 2021 at 15:45 Comment(0)
F
1

This answer might not be helpful for OP but might be useful for others.

If you want to change color of only 1 Preference and not all then u can use HTML, as

  1. Add preference in PreferenceScreen file
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
<Preference app:key="deleteUser"/>
</PreferenceScreen>
  1. Now in the onCreate() method of the class extending PreferenceFragmentCompat you can add title in HTML format as
Preference preference=findPreference("deleteUser");
if (preference!=null) 
preference.setTitle(Html.fromHtml("<span style='color:red;'>Delete User</span>"));

Sample Result : enter image description here

Forerunner answered 11/2 at 11:40 Comment(0)
E
0

A lot of the other answers didn't work for my case. I'm using a PreferenceFragmentCompat and I didn't want to have actual code doing this. So I simply made a copy of the preference category xml file and changed the textColor field. The file goes under the Apache license, Version 2.

<?xml version="1.0" encoding="utf-8"?>

<!--
  ~ Copyright (C) 2015 The Android Open Source Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License -->

  <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginStart="?android:attr/listPreferredItemPaddingLeft"
    android:orientation="vertical">
    <TextView
      android:id="@android:id/title"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginTop="16dp"
      android:paddingEnd="?android:attr/listPreferredItemPaddingRight"
      android:textAlignment="viewStart"
      android:textColor="@color/app_accent"
      android:textStyle="bold"
      tools:ignore="RtlSymmetry"/>
    <TextView
      android:id="@android:id/summary"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:ellipsize="end"
      android:singleLine="true"
      android:textColor="?android:attr/textColorSecondary"/>
  </LinearLayout>

And imported it in my .xml layout for the Preference fragment:

 <PreferenceCategory
    android:layout="@layout/preference_category_companion"
    android:key="my_preference_title"
    android:title="@string/my_preference_title">
Episcopal answered 14/1, 2019 at 8:54 Comment(0)
W
0

This worked for me,

In your AndroidManifest.xml, add the following style:

    <activity
        android:theme="@style/PreferenceScreen"
        android:name="com.yourapp.id"
        android:label="About"
        android:exported="true">
    </activity>

Then go to your styles.xml and add the following:

<style name="PreferenceScreen" parent="Theme.MaterialComponents.Light.DarkActionBar">
    <item name="android:background">#333333</item>          <!--Change color in Preference background-->
    <item name="android:colorAccent">#FFFFFF</item>         <!--Change color in PreferenceCategory title-->
    <item name="android:textColorPrimary">#FFFFFF</item>    <!--Change color in PreferenceCategory->Preference->app:title -->
    <item name="android:textColorSecondary">#BDBDBD</item>  <!--Change color in PreferenceCategory->Preference->app:summary -->
</style>
Willumsen answered 26/2, 2023 at 13:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.