无法创建AlertDialog:AppCompat错误 [英] Cannot create AlertDialog: AppCompat error
问题描述
我正在尝试创建一个AlertDialog,如下所示:
I am trying to create an AlertDialog like this:
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
元素:
I am using an AppCompat theme for my app. Here is the application
element of my AndroidManifest.xml
:
<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
.
但是,每当我运行我的应用程序时,它都会崩溃并显示以下错误消息:
As you can see, my theme is set to @style/Theme.AppCompat.Light.NoActionBar
.
But whenever I am running my app it crashes with the following error message:
java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
我在Google上搜索了很多东西,并在SO上找到了一些类似的问题,但是并没有解决问题.我正在使用AppCompat
主题,所以我在做什么错了?
I googled a lot and found a few similar questions at SO but didn't manage to solve the problem. I am using an AppCompat
theme, so what am I doing wrong?
推荐答案
由于您的主题与您的Activity
有关,因此您必须将其传递为context
到AlertDialog.Builder
-getApplicationContext()
没有主题附加到这就是为什么您遇到错误的原因.
Since your theme is related to your Activity
, you must pass it as the context
to AlertDialog.Builder
- getApplicationContext()
has no theme attached to it which is why you are getting an error.
这篇关于无法创建AlertDialog:AppCompat错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!