如何在Android中的PopupWindow中创建Spinner小部件? 单击Spinner时获取BadTokenException

我一直在网上搜索这个问题的解决方案,但不幸的是,我似乎无法找到答案。 我为PopupWindow创建了一个XML文件,里面有一个Spinner。 在按钮事件监听器中,我调用以下代码来膨胀PopupWindow并在屏幕上显示它。

LayoutInflater inflater = getLayoutInflater(); settings_layout = inflater.inflate(R.layout.setting_popout, (ViewGroup) findViewById(R.id.setting_popout)); // Creates a popup window of required width and height, and displays // the popup in the center of the screen. pw_settings = new PopupWindow(settings_layout, 400, 470, true); pw_settings.showAtLocation(settings_layout, Gravity.CENTER, 0, 0); spColors = (Spinner) settings_layout.findViewById(R.id.linecolor); // Sets the initial values of the color spinner and the listener ArrayAdapter adapter_color = ArrayAdapter.createFromResource(this, R.array.colors_array, android.R.layout.simple_spinner_item); adapter_color.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spColors.setAdapter(adapter_color); spColors.setSelection(adapter_color.getPosition(over.color)); 

单击按钮时,弹出窗口显示正常。 但是,当我单击Spinner时,我在LogCat中收到以下错误。

android.view.WindowManager $ BadTokenException:无法添加窗口 – 令牌android.view.ViewRootImpl$W@41402a90无效; 你的活动在运行吗? …

我不确定我做错了什么。 任何帮助将不胜感激! 谢谢!

它可能有点晚了,并不完全是对原始问题的答案,但我从另一个问题中发现,将以下行插入到我的微调器的xml中可防止发生错误。

android:spinnerMode="dialog"

我现在已经遇到过这个问题了几次,而我发现的唯一非耗时的方法是迈克福斯克上面提出的方法。

 android:spinnerMode="dialog" 

使微调器的选项列表显示在单独的弹出窗口中,这不会使您在代码中打开的初始弹出窗口跳闸。 例如 :

  

尝试:

 settings_layout = inflater.inflate(R.layout.setting_popout, null); ((ViewGroup) findViewById(R.id.setting_popout)).addView(settings_layout); 

另外,为什么要将弹出窗口中的布局附加到活动内部的ViewGroup ? 你有机会逃脱:

 settings_layout = inflater.inflate(R.layout.setting_popout, null);