Search code examples
androidandroid-layoutandroid-theme

Using custom attributes in layout crashes app


I'm building an Android app and I'm trying to apply a custom theming, and I want to use some custom attributes.

I've defined the attrs in the attrs.xml as such:

<resources>
    <attr name="baseColor" format="reference" />
    <attr name="accentColor" format="reference" />
</resources>

and in my styles.xml I've added the following values to my theme:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="android:textColor">@android:color/black</item>
        <item name="android:windowNoTitle">true</item>
        <item name="colorAccent">@color/blue_color</item>
        <item name="android:colorPrimaryDark" tools:targetApi="lollipop">@color/blue_color</item>

        <item name="baseColor">@color/blue_color</item>
        <item name="accentColor">@color/red_color</item>
</style>

Finally, in my XML layout, I'm applying these attributes on a button as such:

<androidx.appcompat.widget.AppCompatButton
            android:id="@+id/sign_up_button"
            android:background="?attr/accentColor"
            android:textColor="?attr/baseColor"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:text="@string/sign_up_button" />

However, when I run my app, it crashes with a java.lang.UnsupportedOperationException: Failed to resolve attribute at index 13: TypedValue{t=0x2/d=0x7f040046 a=-1} which of course means that my custom attribute was not found. Am I missing anything? I've already defined the colors and the attrs in my theme, and I've applied the theme to my activity in my manifest. The full stack trace can be found here


Solution

  • So it turns out the activity that was crashing was using a different theme, which did not have the custom attributes. I've removed the custom theme form the manifest and the attributes work as expected since they are defined in my App's global theme.