我目前正在开发一个android项目,并且上下文和AlertDialogs出现问题。

我有一个扩展Fragment的类,它创建了一个名为Common的标准Java类的实例,该类具有从Fragment传递给它的上下文。在Common类中,我有一些代码来显示警报对话框,并根据用户单击的内容返回布尔值。

通过扩展活动的标准类,我可以使用以下方法创建Common类的实例:

Common common = new Common(this);


然后,可以使用以下代码在此类中调用我的show alert对话框函数。

common.showYesNoDialog("This is my message", false);


对于标准的Activity类,上面的代码可以正常工作。我的问题是这个。

在扩展片段的类中,我无法将this传递给公共类,因此我不得不使用以下代码:

Common common = new Common(getActivity().getApplicationContext());


并且我正常使用以下代码:

common.showYesNoDialog("This is my message", false);


当我调用上面的函数时,出现以下错误:

FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application.


感谢您的任何帮助,您可以提供。

最佳答案

您应该使用getActivity()而不是getActivity().getApplicationContext(),因为getActivity()返回的Activity是Context的子类。

10-08 08:15
查看更多