alertdialog报错,无法创建AlertDialog:AppCompat错误

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(); //

return true;

}

});

I am using an AppCompat theme for my app. Here is the application element of my AndroidManifest.xml:

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/Theme.AppCompat.Light.NoActionBar">

android:name=".MainActivity"

android:label="@string/app_name"

android:screenOrientation="portrait"

>

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.

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?

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值