无法创建 AlertDialog:AppCompat 错误

Cannot create AlertDialog: AppCompat error

我正在尝试创建这样的 AlertDialog:

counterButton.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {

        new AlertDialog.Builder(context)
                .setTitle("Delete entry")
                .setMessage("Are you sure you want to delete this entry?")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // continue with delete
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // do nothing
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();  // <------- crashes here

        return true;
    }
});

我正在为我的应用程序使用 AppCompat 主题。这是我的 AndroidManifest.xml:

application 元素
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

如您所见,我的主题设置为@style/Theme.AppCompat.Light.NoActionBar。 但是每当我 运行 我的应用程序崩溃并显示以下错误消息时:

java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

我用谷歌搜索了很多,在 SO 发现了一些类似的问题,但没有设法解决问题。我使用的是 AppCompat 主题,我做错了什么?

如错误所述

You need to use a Theme.AppCompat theme

然后您将创建样式扩展 AppTheme

!-- Base application theme. -->
<style name="AppTheme" parent="AppTheme.Base"/>

<style name="AppTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->



<activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

由于您的主题与 Activity 相关,您必须将其作为 context 传递给 AlertDialog.Builder - getApplicationContext() 没有附加主题,这就是为什么你收到一个错误。