如何根据其状态设置 SearchView 的样式?

How can I style a SearchView according to its state?

我正在尝试设置 SearchView 的样式,以便在用户聚焦时以不同的方式显示它,就像在亚马逊的应用程序中一样:

专注

不专注

我从 this article 看到从 v21 开始可以使用 styleable 属性来自定义 SearchView 的显示,例如 queryBackground:

<!-- Background for the section containing the search query -->
    <attr name="queryBackground" format="reference" />

我尝试通过我的应用程序样式为此 属性 设置 drawable

风格

<style name="AppTheme.SearchView" parent="Widget.AppCompat.SearchView">
    <item name="queryBackground">@drawable/shape_search</item>
</style>

可绘制

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="false">
        <shape xmlns:android="http://schemas.android.com/apk/res/android"
               android:padding="12dp"
               android:shape="rectangle">
            <solid android:color="#FFF"/>
            <stroke
                android:width="0.3dp"
                android:color="@color/colorAccent"/>
            <corners android:radius="5dip"/>
            <padding android:bottom="0dip" android:left="0dip" android:right="0dip" android:top="0dip"/>
        </shape>
    </item>
    <item android:state_focused="true">
        <shape xmlns:android="http://schemas.android.com/apk/res/android"
               android:padding="12dp"
               android:shape="rectangle">
            <solid android:color="#FFF"/>
            <stroke
                android:width="3dp"
                android:color="@color/colorAccent"/>
            <corners android:radius="5dip"/>
            <padding android:bottom="0dip" android:left="0dip" android:right="0dip" android:top="0dip"/>
        </shape>
    </item>
</selector>

然而,这并没有按预期工作:第一种样式总是被选中,无论我是否关注 SearchView。 我尝试使用其他状态选择器,如 state_active 甚至 state_window_focused,当视图的 window 具有输入焦点 时提到 ,但在每种情况下都将焦点放在 SearchView没有改变它的显示。

有没有办法在这两种状态下以不同方式显示此 SearchView?

现在是 2018 年 5 月 6 日 我认为您已经找到了适合您的解决方案,但我认为我的回答可能对其他人有帮助 我用的是kotlin,如果你用java,也是一样的

在您看来(activity,片段,..):

 svSearch.setOnQueryTextFocusChangeListener(object : View.OnFocusChangeListener {
        override fun onFocusChange(v: View?, hasFocus: Boolean) {
            svSearch.isSelected =  hasFocus
            // isIconified() return true if search view lost focus, this line handle for user press back button case
            // as default when user press back button, the search view lost focus but view doesn't change state (collapse if width = wrap_content) 
            svSearch.isIconified = !hasFocus
        }

 })

选择器:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="false">
       // something 
    </item>
    <item android:state_selected="true">
       // something 
    </item>
</selector>