How do I change the textColorPrimary in a theme?

2020-07-07 00:56发布

问题:

I'm changing the theme of an activity in onCreate using setTheme (I'm doing that even before calling super.onCreate(), as this is supposed to be more reliable).

It does work in the sense that it changes the background and foreground colors. However, my layout has a few elements that use styles like textAppearanceLarge. Now Android's textAppearanceLarge internally uses the textPrimaryColor - which is still unchanged by my theme.

I tried to override the primary text color in my theme, but that doesn't seem to work.

Here is the crucial part of the theme:

<style name="Theme.MyApp.White">
   <item name="android:background">@android:color/white</item>
   <item name="android:textColor">#000000</item>
</style>

The background appears white, plain TextViews appear black... but TextViews using textAppearanceLarge are white, and as such invisible (white on white).

I tried things like this:

   <item name="android:ColorPrimary">#000000</item>
   <item name="android:textColorPrimary">#000000</item>
   <item name="android:attr/textColorPrimary">#000000</item>

But none of those do anything. What's the magic trick?

回答1:

Just as a workaround, Instead of using textAppearanceLarge in the layout, (if you're using xml to build the layout), define your own textAppearanceLarge style in the styles.xml that emulates the android default one except you can change the color to white.

xml layout:

<!-- example textview -->
<TextView style="@style/large" android:text="text goes here"></TextView>

then in the styles.xml

<style name="large">
    <item name="android:textColor">@android:color/white</item>
    <!-- other necessary items here like font etc.-->
</style>


回答2:

The only difference between "style" and "theme" is the scope at which a style is applied at. A style applied to an Activity is called a Theme.

Here's a good writeup on the topic : http://brainflush.wordpress.com/2009/03/15/understanding-android-themes-and-styles/



回答3:

Turns out I was barking up the wrong tree. Overriding the colors and everything worked just fine. However, by defining android:background in my theme, everything just completely messed up, and all text appeared white, despite me overriding all colors (including textColorPrimary). Omitting android:background did the trick.