Setting up parameter by reference is throwing UnsupportedOperationException

198 Views Asked by At

I want to set parameters by reference. In my case, it is color that will switch by custom app Theme. Problem is that at one place in my code it is throwing UnsupportedOperationException but in other places it is working fine. I'm using it in 50 different places but just here in this layout, it is not working. Probably problem is that it is layout which is inflated by LayoutInflater.

Here is my color name in attr.xml ->

<attr name="bgColor" format="reference"/>

Here is usage in styles.xml inside my custom Theme:

<style name="AppThemeBlueDark" parent="Theme.MaterialComponents.Light.NoActionBar.Bridge">
   ...
   <item name="bgColor">@color/darkred</item>
   ...
</style>

Here is usage of this referenced color in XML layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="52dp"
    android:gravity="center"
    android:background="?attr/bgColor">
    ...
    Other Views
    ...
</LinearLayout>

Exception:

Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 13: TypedValue{t=0x2/d=0x7f030051 a=-1}
        at android.content.res.TypedArray.getDrawableForDensity(TypedArray.java:946)
        at android.content.res.TypedArray.getDrawable(TypedArray.java:930)
        at android.view.View.<init>(View.java:5012)
        at android.view.ViewGroup.<init>(ViewGroup.java:660)
        at android.widget.LinearLayout.<init>(LinearLayout.java:244)
        at android.widget.LinearLayout.<init>(LinearLayout.java:240)
        at android.widget.LinearLayout.<init>(LinearLayout.java:236)
1

There are 1 best solutions below

4
On

Change below line

<attr name="bgColor" format="reference"/>

to

<attr name="bgColor" format="color"/>

And use android:backgroundTint="?attr/bgColor" insted of android:background="?attr/bgColor"