不显示警报对话框
大家好,我正在通过单击按钮在 android 中创建一个警报对话框。我使用了 XML 的 onClick 属性和调用函数。我的代码是
public void selectPhoneType(View view)
{
String [] item = {"Home", "Work", "Mobile", "Work Fax", "Home Fax", "Pager", "Other", "Custom"};
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle("Select Label");
AlertDialog alert = builder.create();
alert.show();}
,但此代码没有显示警报并给出错误,例如
BadTokenException: Unable to add window -- token null is not for an application.
请告诉我此代码有什么问题。
Hi all I am creating an alert dialog in android by clicking a button. I used onClick property of XML and calling function. My code is
public void selectPhoneType(View view)
{
String [] item = {"Home", "Work", "Mobile", "Work Fax", "Home Fax", "Pager", "Other", "Custom"};
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle("Select Label");
AlertDialog alert = builder.create();
alert.show();}
but this code is not showing alert and giving error like
BadTokenException: Unable to add window -- token null is not for an application.
Please tell me what is wrong with this code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为这就是问题所在。你有没有尝试过:
I think this is the problem. Have you tried:
传递
requireActivity()
而不是requireContext()
对我有用..!!我认为这需要活动背景!
Passing
requireActivity()
instead ofrequireContext()
worked for me..!!I think it requires activity context!!.
如果您在后台线程中调用对话框代码,那么它将无法工作。
你应该在主线程中调用UI相关的代码,如果你不这样做,那么它不会向你显示对话框。
如果您想在后台任务中显示对话框,请改用处理程序。
new Handler().post(new Runnable(){
显示对话框();
})
确保调用了
create()
和show()
方法。永远不要忘记第一点和第二点。
If you are calling dialog code in background thread then it won't work.
You should call UI related code in main thread, if you are not doing it then it will not show you the dialog.
If you want show the dialog in the background task then use handler instead.
new Handler().post(new Runnable(){
showDialog();
})
Make sure
create()
andshow()
method is called.Never forgot 1st and 2nd point.
就我而言,用
android.app.AlertDialog
替换androidx.appcompat.app.AlertDialog
帮助了我:In my case, replacing
androidx.appcompat.app.AlertDialog
byandroid.app.AlertDialog
helped me:Activity_main.xml-
MainActivity.kt-
Activity_display.xml-
Display.kt-
activity_main.xml-
MainActivity.kt-
activity_display.xml-
Display.kt-