如何显示 MaterialAlertDialog?

How do I display a MaterialAlertDialog?

我正在将我的应用程序的主题从 AppCompat 更改为 MaterialComponents,除提醒对话框外,其他一切都正常。我已经在样式和清单中将应用主题设置为 MaterialComponents

样式

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="colorPrimary">@color/grey</item>
    <item name="colorPrimaryDark">@color/black</item>
    <item name="colorAccent">@color/red</item>
    <item name="colorSurface">@color/white</item>
    <item name="colorOnSecondary">@color/white</item>
    <item name="colorSecondary">@color/red</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.MaterialComponents.Dark.ActionBar"/>
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.MaterialComponents.Light"/>

build.gradle

implementation 'com.google.android.material:material:1.1.0'

AndroidManifest

<application
    android:allowBackup="true"
    android:fullBackupContent="false"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:ignore="GoogleAppIndexingWarning">

这是我试图显示对话的代码:

MaterialAlertDialogBuilder(context)
            .setTitle(R.string.tip_title)
            .setMessage(R.string.tip)
            .setNeutralButton(R.string.ok, null)
            .setPositiveButton(R.string.do_not_show_again) { _, _ ->
                preferencesHelper.disableTip()
            }.show()

最后,我得到的错误是

java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.AppCompat (or a descendant).

我该如何解决这个错误?

显示对话的函数将 Context 作为其输入参数,这又是应用程序上下文注入函数所在的 class。

我设法通过将函数中的输入参数类型更改为 Activity 来解决问题,这是一种强制执行正确主题的方法。