简体   繁体   English

警报对话框未显示

[英]Alert dialog is not displaying

Hi all I am creating an alert dialog in android by clicking a button.大家好,我正在通过单击一个按钮在 android 中创建一个警报对话框。 I used onClick property of XML and calling function.我使用了 XML 的 onClick 属性和调用函数。 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.请告诉我这段代码有什么问题。

new AlertDialog.Builder(getApplicationContext());

I think this is the problem.我认为这是问题所在。 Have you tried:你有没有尝试过:

new AlertDialog.Builder(YourActivityClassName.this);

Passing requireActivity() instead of requireContext() worked for me..!!传递requireActivity()而不是requireContext()对我有用..!! I think it requires activity context!!.我认为它需要活动上下文!

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.您应该在主线程中调用与 UI 相关的代码,如果您不这样做,那么它不会向您显示对话框。

  1. If you want show the dialog in the background task then use handler instead.如果要在后台任务中显示对话框,请改用处理程序。

    new Handler().post(new Runnable(){ showDialog(); })新的 Handler().post(新的 Runnable(){ showDialog(); })

  2. Make sure create() and show() method is called.确保调用了create()show()方法。

  3. Never forgot 1st and 2nd point.永远不要忘记第 1 点和第 2 点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM