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.