Inheritance issue, when using property androidText

2019-06-14 16:17发布

问题:

I have a root theme and an inheriting child theme:

<resources>
    <color name="colorRed">#FF0000</color>
    <color name="colorGreen">#00FF00</color>

    <style name="Root" parent="Theme.AppCompat.Light.DarkActionBar" />

    <style name="Root.TextAppearance" parent="android:TextAppearance">
        <item name="android:textColor">@color/colorGreen</item>
    </style>

    <style name="Child" parent="Root">
        <item name="android:textColor">@color/colorRed</item>
    </style>

</resources> 

In the manifest file I set the theme Child. In the layout I apply the text appearance from the root theme:

<TextView
    android:textAppearance="@style/Root.TextAppearance"
    android:text="Hello World!"
  • Expected: green text
  • Actual: red text

How does the Root.TextAppearance inherit the color red?

回答1:

You should set the style not the textAppearance

style="@style/Root.TextAppearance"

also in styles Root.TextAppearance should have Root as parent

<style Root.TextAppearance parent="android:TextAppearance">

than set android:textAppearance="@style/Root.TextAppearance" and it should work



回答2:

make some change put color code into color.xml

    <color name="colorRed">#FF0000</color>
<color name="colorGreen">#00FF00</color>

then after try this..

        android:textAppearance="@style/Root.TextAppearance"


回答3:

Checking the order of precedences

The short answer to the question is, that themes have precedence over android:textAppearance.

There are different types of hierarchies for Android. When using the styles attribute the styles hierarchy applies as expected. Assuming that the styles hierarchy also applies for the android:textAppearance attribute obviously fails.

There is another hierarchy for themes. This hierarchy follows down the layout tree. The theme Child is applied in the manifest and is the top level.

It seems the settings coming in by this top level theme even overrule the settings of android:textAppearance on a lower level. This still feels wrong, as lower levels usually should overwrite higher levels.

So I do some tests by applying the attributes style, android:theme and android:textAppearannce to find out the order of their strengths.

It turns out that texAppearance is the weakest and style is the strongest:

  1. style
  2. android:theme
  3. android:textAppearance

I think this the explanation why the theme from the higher level could overwrite the android:textAppearance on the lower level. I admit that I find the low precedence of textAppearance rather confusing. It's not how I expected it to work. However, that's the results I found out be testing.