首页 > 解决方案 > 为什么 android.widget.SearchView 在单击时不展开,而是将图标移动到左侧?

问题描述

我在android.widget.SearchView里面使用MaterialToolbar并且还在菜单资源文件中设置了正确的属性。但是当我点击搜索图标时,它并没有展开。相反,搜索图标移动到左侧。再次单击它时,它会展开,但搜索图标仍会出现在 EditText 中。


布局文件

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/toolbar"
        style="@style/Widget.MaterialComponents.Toolbar.Primary"
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize"
        app:title="@string/app_name" />

</com.google.android.material.appbar.AppBarLayout>

菜单文件

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_search"
        android:title="@string/action_search"
        android:icon="@drawable/ic_search"
        app:showAsAction="ifRoom|collapseActionView"
        app:actionViewClass="android.widget.SearchView" />

</menu>


点击之前

点击之前

点击后

点击后

搜索查看提示

标签: androidtoolbarsearchview

解决方案


尽管文档建议使用 framework SearchView,但我一直发现 support/androidxSearchView与库组件(例如 、AppCompatActivity等)配合得更好,MaterialToolbar尽管我不确定导致这些小故障的确切原因。确实,使用androidx.appcompat.widget.SearchView此处代替了android.widget.SearchViewactionViewClass扩展时摆脱了那个放错位置的搜索图标。

但是,AutoCompleteTextView内部SearchView仍然有一个类似的搜索图标作为提示,因为它没有以正确的样式结束。我最初预计将 设置Toolbar为支持ActionBar会将其与儿童的其他相关样式整合在一起,但似乎'的SearchView样式由于某种原因通常设置为.ThemeOverlay.*.ActionBar<*Toolbar>ActionBar

尽管大多数消息来源似乎表明各种ThemeOverlay.*.ActionBar样式仅调整colorControlNormal属性,但它们实际上也将 设置searchViewStyle为适当的Widget.*.SearchView.ActionBar值,因此添加适当的叠加层非常重要。例如,与更改为androidx版本保持一致:

<com.google.android.material.appbar.MaterialToolbar
    android:id="@+id/toolbar"
    android:theme="@style/ThemeOverlay.MaterialComponents.Dark.ActionBar"
    ... />

这也可以通过将其设置为actionBarThemeActivity的主题来实现,但请注意,它可以被<*Toolbar>自身的属性覆盖,就像在给定的设置中一样style="@style/Widget.MaterialComponents.Toolbar.Primary"

如果您不使用材质组件,ThemeOverlay.AppCompat也可以使用样式。如果你只使用平台类,在系统命名空间中可以使用类似的样式;例如,@android:style/ThemeOverlay.Material.Dark.ActionBar


该答案的初始修订版手动删除了该提示图标,因为当时我不知道给定设置究竟是如何失败的。现在不需要这样做,但是如果您想进一步自定义它,该示例只需将 menu<item>app:actionViewClass属性替换为app:actionLayout指向此布局的属性:

<androidx.appcompat.widget.SearchView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/search_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:searchHintIcon="@null" />

searchHintIcon设置是此处示例所需的全部内容,但您可以设置任何SearchView您想要的适用属性。

如果你要走这条路,最好设置style="@style/Widget.AppCompat.SearchView.ActionBar",其中包括searchHintIcon设置,并确保正确的整体风格SearchView,正如 Artem Mostyaev 在下面的评论中所建议的那样。


推荐阅读