[英]Alert dialog is not displaying
大家好,我正在通过单击一个按钮在 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.
请告诉我这段代码有什么问题。
new AlertDialog.Builder(getApplicationContext());
我认为这是问题所在。 你有没有尝试过:
new AlertDialog.Builder(YourActivityClassName.this);
传递requireActivity()
而不是requireContext()
对我有用..!! 我认为它需要活动上下文!
如果您在后台线程中调用对话框代码,那么它将不起作用。 您应该在主线程中调用与 UI 相关的代码,如果您不这样做,那么它不会向您显示对话框。
如果要在后台任务中显示对话框,请改用处理程序。
新的 Handler().post(新的 Runnable(){ showDialog(); })
确保调用了create()
和show()
方法。
永远不要忘记第 1 点和第 2 点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.