Search code examples
androidandroid-theme

ThemeEnforcement error actually caused by unset attrs


I'm getting a ThemeEnforcement error with the following. warnings.

 Caused by: android.view.InflateException: Binary XML file line #9 in com.yourproject:layout/app_bar_main: Error inflating class com.google.android.material.appbar.AppBarLayout

 Caused by: java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.AppCompat (or a descendant).

Typical solutions suggest that i'm not applying Theme.AppCompat to my app theme. except i Am.

<style name="Theme.TestApp" parent="Theme.AppCompat">


</style>

Also, other solutions suggest this is caused by not including the appropriate material libraries, which are included and i have previously been able to successfully compile and run the project.

The project compiles with no errors but in some instances the app will crash out immediatly but in other instances (where i have disabled some components) the crash will happen when layout out other views.

In the latter crashes, the error may have issues inflating a standard Button or TextField.


Solution

  • TLDR not setting custom attr values which are used in layouts causes this error.

    Part of the problem was that the error messaging was specifically stating that the problem was i wasn't applying the Theme.AppCompat, but in fact I was.

    What I wasn't aware of however was that a nav_header_main.xml file was applying the style AppMenuTitle to a Textfield.

    This Style was consuming a custom attribute called my.custom.attr. The issue was caused by the fact that this attr's value had not be set in the theme. So it was essentially null.

    <style name="AppMenuTitle" parent="ThemeOverlay.AppCompat.Dark">
        <item name="android:textColor">?my.custom.attr</item>
        <item name="android:textStyle">bold</item>
        <item name="android:textSize">18sp</item>
    </style>
    

    Now because these attr values were being used in a number of places, I also got errors for inflating your standard Button. And this got really confusing because the buttons were just straight up buttons, with no styling applied directly.

    In stead, buttons where obtaining there styles from themes applied to parent containers, whos styles had the buttonStyle properties set.

    These buttons were using custom drawables. Which guess what, were also using custom attribute values, which guess what....where also not set in the theme.

    Ensuring these custom attrs had values, resolved the error.

    <style name="Theme.TestApp" parent="Theme.AppCompat">
        <item name="my.custom.attr.used.in.textstyle">@color/black</item>
        <item name="my.custom.attr.used.in.drawable">@color/black</item>
    </style>