Material-components-android: [MaterialAlertDialogBuilder] Crash building dialog with Material Components app theme

Created on 2 Feb 2020  路  4Comments  路  Source: material-components/material-components-android

Description: Attempting to build a AlertDialog using the MaterialAlertDialogBuilder causes the app to crash in a AppCompatActivity, even though the application theme is set to a Material Components theme.

Stacktrace

java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.AppCompat (or a descendant).
        at com.google.android.material.internal.ThemeEnforcement.checkTheme(ThemeEnforcement.java:243)
        at com.google.android.material.internal.ThemeEnforcement.checkAppCompatTheme(ThemeEnforcement.java:213)
        at com.google.android.material.internal.ThemeEnforcement.checkCompatibleTheme(ThemeEnforcement.java:148)
        at com.google.android.material.internal.ThemeEnforcement.obtainStyledAttributes(ThemeEnforcement.java:76)
        at com.google.android.material.dialog.MaterialDialogs.getDialogBackgroundInsets(MaterialDialogs.java:60)
        at com.google.android.material.dialog.MaterialAlertDialogBuilder.<init>(MaterialAlertDialogBuilder.java:117)
        at com.google.android.material.dialog.MaterialAlertDialogBuilder.<init>(MaterialAlertDialogBuilder.java:103)
        at ninja.hassie.uni.todo.MainActivity$2.handleFault(MainActivity.java:69)
        at com.backendless.Persistence$1.handleFault(Persistence.java:189)

Expected behavior: The dialog should build as the app theme is set to a Material Components theme.

Source code:
styles.xml

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorSecondary">@color/colorAccent</item>
    </style>
</resources>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    ...
    new MaterialAlertDialogBuilder(getApplicationContext())
         .setMessage("Successfully added task")
         .setPositiveButton(android.R.string.ok, null)
         .show();

Android API version: 9 Pie

Material Library version: 1.2.0-alpha04

Device: OnePlus 5T

bug wontfix

Most helpful comment

Hi @hassieswift621 - The application's context isn't guaranteed to have the theme, so you'll either need to call setTheme on it or use the Activity's context.

All 4 comments

Hi @hassieswift621 - The application's context isn't guaranteed to have the theme, so you'll either need to call setTheme on it or use the Activity's context.

Thanks 馃槃

Fixed my issue! Thanks

What?

Was this page helpful?
0 / 5 - 0 ratings