Reputation: 4532
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
Upvotes: 1
Views: 894
Reputation: 4532
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.
Upvotes: 4
Reputation: 3099
For your custom button you need to declare styleable in attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="UpdateButton">
<attr name="setType" format="string" />
<attr name="setContent" format="string"/>
</declare-styleable>
</resources>
Your styleable name being the Class name of your custom view.
For building a custom theme to expand upon your comment you can swap around themes rather than using attrs.xml
Change Current Theme At Runtime - Stackoverflow
Upvotes: -1