首页 > 解决方案 > AutoCompleteTextView - 在弹出窗口可见时旋转设备时崩溃

问题描述

每当我在显示 AutoCompleteTextView 下拉菜单时旋转设备时都会遇到崩溃。

我每次都可以通过以下方式重新创建它:

  1. 点击 AutoCompleteTextView 以显示建议下拉菜单
  2. 不做选择
  3. 旋转设备

堆栈跟踪:

     Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?

布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior">

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/criteria_text_input_layout"
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Name"
    app:errorEnabled="true">

    <AutoCompleteTextView
        android:id="@+id/criteria_text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:ignore="LabelFor" />

</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>

我已经搜索了该异常,并且当您使用 getApplicationContext() 时似乎会发生这种情况,但我所有的适配器都使用 getContext()。我也尝试过关闭配置更改的下拉菜单,但无济于事。有任何想法吗?

标签: androidautocompletetextview

解决方案


原来这是三星设备的问题(这是我用来测试的)。我无法准确找出问题在代码中的位置,但我确实注意到日志中有一个错误:

sendUserActionEvent() mView == null

因此,我又进行了一次搜索,发现它是某些 Android 设备上的一个已知错误,其中 mView 可以为空,因此建议的解决方案之一是将以下内容添加到清单中:

android:configChanges="orientation|screenSize"

这似乎解决了我的问题。

编辑: 使用它会引入另一个问题,因为旋转设备不再允许我正确恢复状态。所以我现在回到了第一方。

编辑#2: 似乎这个问题发生在恢复 TextInputLayout 和 AutoCompleteTextView 的状态期间。另一种解决方案是通过将以下内容添加到视图来禁用状态保存:

    android:saveEnabled="false"

通过添加它并删除上面的 configChanges,我可以按预期恢复状态。


推荐阅读