如何像 Google Play 商店应用中那样设置 Android SearchView 的样式?

How to style Android SearchView like in Google Play Store app?

我正在尝试将 toolbar 中的 SearchView 设置为看起来/表现得像 Google Play Store app 中的 SearchView。它似乎将搜索视图包装在卡片视图中,但它似乎也集成了向上按钮/抽屉切换行为。

这是主要的 activity searchView,它集成了抽屉开关

当您点击它时,抽屉开关会变为箭头(点击后会从搜索视图中移除焦点)

当您在商店中点击一个应用程序时,您会转到应用程序详细信息页面,并且您会看到类似图标化版本的搜索视图作为带有向上按钮的折叠操作项:

最后,如果您单击搜索图标,它会展开为一个操作项(带有一种波纹动画)并显示在整个屏幕上并包含向上按钮:

当我尝试自己做时,我遇到了很多问题。我试图将 searchview 包装在 cardview 中并将其放在工具栏中。它有效,但左侧总是有我无法删除的填充(我尝试了 contentInsetStart,但不起作用):

<android.support.v7.widget.Toolbar
    android:id="@+id/activityCatalogToolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:popupTheme="@style/AppTheme.PopupOverlay"
    android:theme="@style/AppTheme.AppBarOverlay"
    app:contentInsetStart="0dp"
    app:contentInsetLeft="0dp">

    <android.support.v7.widget.CardView
        android:id="@+id/activityCatalogSearchContainer"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:layout_gravity="end"
        android:layout_marginTop="4dp"
        android:layout_marginBottom="4dp"
        android:layout_marginRight="8dp"
        android:layout_marginLeft="8dp"
        app:cardCornerRadius="4dp"
        app:cardElevation="8dp">

        <android.support.v7.widget.SearchView
            android:id="@+id/activityCatalogSearch"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:queryHint=""
            android:iconifiedByDefault="false"/>

    </android.support.v7.widget.CardView>

</android.support.v7.widget.Toolbar>

我也曾尝试删除工具栏并仅用 FrameLayout 替换它。这允许我控制填充,但显然我失去了工具栏功能(向上按钮等)并且还引入了主题问题(图标和文本消失)。

有人知道他们是怎么做到的吗?我不想添加另一个库来为框架中已经存在的小部件设置样式。谢谢!

您必须使用 SearchView 的自定义实现。

https://github.com/Quinny898/PersistentSearch

Android工作室:

如果您还没有,请添加 Sonatype 存储库:

maven {
        url "https://oss.sonatype.org/content/repositories/snapshots"
    }

将其作为依赖项导入:

compile 'com.quinny898.library.persistentsearch:library:1.1.0-SNAPSHOT'

在您的布局中:

<com.quinny898.library.persistentsearch.SearchBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/searchbox"
        />

输出:

您可能会尝试深入研究这个项目:

https://android.googlesource.com/platform/packages/apps/Dialer/

对于 Lollipop 或 Marshmallow,或者 N,它有一个 SearchEditTextLayout,这就是您所需要的:

优势

  • 由 Google 而非第三方制作的代码。

我自己正在尝试构建它。最后只是将搜索按钮设为 ImageButton。单击此按钮将触发一个要添加到顶部的片段,该片段将在看起来像这样的布局中包含一个 Edittext。此 Fragment 包含此搜索框下方的列表视图,用于显示建议。

提示:保持 Fragment 的根布局没有任何背景,并将 clickable 设置为 true 以获得透明窗格的最佳效果