【问题标题】:How to create a Spinner widget inside of a PopupWindow in Android? Get BadTokenException when clicking on Spinner如何在 Android 的 PopupWindow 内创建 Spinner 小部件?单击 Spinner 时获取 BadTokenException
【发布时间】:2019-05-28 19:24:31
【问题描述】:

我一直在网上搜索此问题的解决方案,但不幸的是,我似乎找不到答案。我为其中带有 Spinner 的 PopupWindow 创建了一个 XML 文件。在按钮事件侦听器中,我调用以下代码来膨胀 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<CharSequence> 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 无效;您的活动正在运行吗? ...

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

【问题讨论】:

标签: java android spinner popupwindow


【解决方案1】:

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

android:spinnerMode="dialog"

【讨论】:

  • 这不适用于 api 级别 Android 25。
【解决方案2】:

我已经多次遇到这个问题,我发现唯一不耗时的方法是上面 Mike Fosker 提出的方法。

android:spinnerMode="dialog"

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

<Spinner
android:id="@+id/myspinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:spinnerMode="dialog" />

【讨论】:

  • 你可以在这里添加配置或代码示例吗?链接可以删除。
【解决方案3】:

试试:

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);

【讨论】:

  • 没错,我不需要上面的 (ViewGroup) 部分(弹出窗口仍然显示没有该部分)。但是,不幸的是,单击 Spinner 时仍然会出现相同的问题,BadTokenException。不过谢谢!
  • 当Popup出现时,你finish()Activity是不是碰巧了?您可以发布您的 onClick 按钮以显示弹出窗口吗?
  • 不,很遗憾,我没有。但可以肯定的是,我会在原始问题中发布其余的 onClick。我现在只发布了我认为相关的代码。
  • 考虑我的其他评论,使用 ListPopUpWindow...stackoverflow.com/questions/11420609/…
  • 非常感谢您的帮助!虽然我不知道如何使用 ListPopupWindow,但您的评论使我使用对话框(没有标题)而不是普通的 PopupWindow。使用对话框解决了问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多