Search code examples
javaandroidmaterial-designandroid-themeandroid-chips

CreateFromRessource ChipDrawable : The style on this component requires your app theme to be Theme.MaterialComponents


With using AppCompat and using min sdk version 21, I try to use ChipDrawable to use in a list of email adresse in a TextEdit, and I create that ChipDrawable with :

ChipDrawable chip = ChipDrawable.createFromResource(getApplicationContext(), R.xml.email_chip);

using this xml :

<?xml version="1.0" encoding="utf-8"?>
<chip xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:chipBackgroundColor="?colorAccent"
    app:closeIconEnabled="true"
    app:closeIconTint="@android:color/white" />

My theme use Theme.MaterialComponents.DayNight.DarkActionBar (and I also tryed Theme.MaterialComponents.DayNight.DarkActionBar.Bridge)

But I always get this error :

The style on this component requires your app theme to be Theme.MaterialComponents (or a descendant).

I tryed everything I found on stackoverflow but it didn't helped much.

Here is my style

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.Mareu" parent="Theme.MaterialComponents.DayNight.DarkActionBar.Bridge">
        <!-- Primary brand color. -->
        <item name="colorPrimary">#4E92DF</item>
        <item name="colorPrimaryVariant">#3F7ABD</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
    </style>
</resources>

Here is part of my graddle

dependencies {
    // Extra
    implementation 'org.greenrobot:eventbus:3.1.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'com.google.android.material:material:1.2.1'

    // Compat
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

    // TU TI
    testImplementation 'org.hamcrest:java-hamcrest:2.0.0.0'

    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

Solution

  • The issue is here:

    ChipDrawable chip = ChipDrawable.createFromResource(getApplicationContext(),
    

    The ApplicationContext doesn't have your app theme.
    You need to pass the Activity, not an Application Context.