Search code examples
androidcolorsstylestextviewthemes

Android: change color of disabled text using Theme/Style?


I have the following colors defined in my color.xml:

<color name="gold">#d49e43</color>
<color name="gold_disabled">#80d49e43</color>

And the following theme:

<style name="Theme.Example" parent="@style/Theme.Sherlock">       
    <item name="android:textColor">@color/gold</item>
</style>

In my SettingsActivity, I have a CheckBoxPreference and a Preference that depends on it. When The CheckBoxPreference is unchecked, the Preference is disabled, however, because of the custom gold text color that I set, it doesn't get "greyed out" like it does with the default color. How do I change this in XML? I've tried setting:

    <item name="android:textColorPrimaryDisableOnly">@color/gold_disabled</item>
    <item name="android:textColorPrimaryInverseDisableOnly">@color/gold_disabled</item>
    <item name="android:textColorPrimaryNoDisable">@color/gold_disabled</item>
    <item name="android:textColorSecondaryNoDisable">@color/gold_disabled</item>
    <item name="android:textColorPrimaryInverseNoDisable">@color/gold_disabled</item>
    <item name="android:textColorSecondaryInverseNoDisable">@color/gold_disabled</item>

but nothing seems to work.


Solution

  • I figured this out more or less by accident, but if you subclass Preference and override the onBindView(), you can achieve the "grayed out" effect when a preference is disabled:

    @Override
    protected void onBindView(View view) {
        // TODO Auto-generated method stub
        super.onBindView(view);
        TextView title = (TextView)view.findViewById(android.R.id.title);
        TextView summary = (TextView)view.findViewById(android.R.id.summary);
    
        if (title.isEnabled()) {
            title.setTextColor(getContext().getResources().getColor(R.color.gold));
        }
        else {
            title.setTextColor(getContext().getResources().getColor(R.color.gold_disabled));
        }
    
        if (summary.isEnabled()) {
            summary.setTextColor(getContext().getResources().getColor(R.color.orange));
        }
        else {
            summary.setTextColor(getContext().getResources().getColor(R.color.orange_disabled));
        }
    }