I'm trying to make a MaterialAlertDialog but I keep getting the following error no matter what
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 com.adamm.quem.MainActivity$1.onItemClick(MainActivity.java:118)
I am using a custom theme as my MainActivity theme which is a parent of MaterialComponents
<style name="MainMaterialTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
Changing the theme to AppCompat doesn't help and isn't really right to do I am following the implementation as Material IO explains https://material.io/develop/android/components/dialog/
My code:
AlertDialog.Builder builder = new MaterialAlertDialogBuilder(getApplicationContext())
.setTitle("Title")
.setMessage("Message")
builder.show();
How can this be fixed?
You're passing in getApplicationContext()
and the application context doesn't have your theme. Pass in your activity as the context:
AlertDialog.Builder builder = new MaterialAlertDialogBuilder(MainActivity.this)
.setTitle("Title")
.setMessage("Message")
builder.show();