Search code examples
androidandroid-stylesandroid-api-levels

style and theme support for lower APIs


The following

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="fontFamily">@font/myfont</item>
</style>

works fine but the following

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="android:fontFamily">@font/myfont</item>
</style>

requires API level 16.

Now i am confused, am i just hiding the error by removing android: prefix or will this work fine on android 4.0?


Solution

  • First, let's consider how attributes work in a layout. If you're using the support library to handle font families, you'd write something like this:

    <TextView
        app:fontFamily="@font/myfont"
        .../>
    

    If, on the other hand, you were using the framework API (which only exists on API 16+), you'd write this:

    <TextView
        android:fontFamily="@font/myfont"
        .../>
    

    When you're creating styles, anything that would have used the app: namespace in a layout simply doesn't get any namespace at all. So a style specifying

    <item name="fontFamily">
    

    would correspond to the first example above, while a style specifying

    <item name="android:fontFamily">
    

    would correspond to the second example above.

    Whichever one you choose to use should be guided by this principle. If you're using the support library, then dropping the namespace is a good thing to do. If you're not using the support library, then dropping the namespace is a bad thing to do.

    tl;dr: Dropping the namespace is a good idea in this situation.