大家好,我正在通过单击按钮在 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相关的代码,如果你不这样做,那么它不会向你显示对话框。
如果您想在后台任务中显示对话框,请改用处理程序。
new Handler().post(new Runnable(){ 显示对话框(); })
确保调用
create()
和 show()
方法。
永远不要忘记第一点和第二点。
就我而言,将
androidx.appcompat.app.AlertDialog
替换为 android.app.AlertDialog
帮助了我:
val builder = android.app.AlertDialog.Builder(requireActivity())