Search code examples
androidpreferenceactivitypreferencepreferencescreen

How to change Preference text colour programmatically?


I'm adding preferences programmatically to my instance of PreferenceScreen (which I add to my PreferenceActivity). Everything works as expected except for the text colour, which always is white despite trying:

  • To set the theme through manifest
  • Set the theme programmatically
  • A few other hacks that aren't notable

All I'm doing:

    PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(this);

    PreferenceCategory category = new PreferenceCategory(this);
    category.setTitle("Hello");

    screen.addPreference(category);

    CheckBoxPreference testPreference = new CheckBoxPreference(getApplicationContext());
    testPreference.setTitle("Test");
    category.addPreference(testPreference);

    setPreferenceScreen(screen);

I've set the theme to ThemeOverlay.AppCompat.Dark (which I don't want) and the text is legible, but this is what it looks like in any other case (I'm tapping it so you can see the text through the animation effect): enter image description here

How would I go about making this text black?

Thanks!


Solution

  • Simple fix, actually:

    I had called getApplicationContext() in CheckBoxPreference testPreference = new CheckBoxPreference(getApplicationContext()); which is not recommended for inflating views as it will almost always pass the wrong theme.

    So, I changed getApplicationContext() to this and it loaded the text colour as what was described in the theme.