I'm trying to create AlertDialog
from RecyclerView.Adapter
with this code
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(context, R.style.AppTheme));
alertDialogBuilder.setView(R.layout.reserve_dialog);
alertDialogBuilder.create();
alertDialogBuilder.show();
but I'm getting this error in logcat:
Theme: themes:{}
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
What is wrong?
Instead of getApplicationContext(), just use ActivityName.this.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.AppTheme));
alertDialogBuilder.setView(R.layout.reserve_dialog);
alertDialogBuilder.create();
if(!isFinishing()){
alertDialogBuilder.show();
}
you are passing context.getApplicationContext()
Instead of this pass activity context
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.AppTheme));
alertDialogBuilder.setView(R.layout.reserve_dialog);
alertDialogBuilder.create();
alertDialogBuilder.show();
删除getApplicationContext()并传递活动上下文。
Inside New Dialogue(youractivity.this, style)
Hopefully it ll solved
If you are creating the dialog inside the RecylerView.Adapter
, pass the activity object in the constructor of the Adapter and use the object itself when creating the builder -
if (!activity.isFinishing()) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.AppTheme));
alertDialogBuilder.setView(R.layout.reserve_dialog);
alertDialogBuilder.create();
alertDialogBuilder.show();
}
When you are displaying a dialog in a non activity class then you have to pass activity as a parameter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.