在 XML 中设置 SearchView 宽度和提示颜色

Set SearchView width and hint color in XML

我已将 SearchView 功能添加到工具栏,我想在展开时使其全宽,并将提示文本颜色更改为白色而不是黑色。 最后我已经能够用这个以编程方式完成它:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    // Associate searchable configuration with the SearchView
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setMaxWidth(4000);
    ((EditText)searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text)).setHintTextColor(getResources().getColor(R.color.md_text_white));
    searchView.setIconifiedByDefault(false);
    return true;
}

有什么方法可以通过 xml 或其他配置中的样式来实现这一点?我更喜欢独立的功能和样式。

我已尝试使用 searchViewStyle 并为 SearchView 创建自定义样式,但没有成功:

<style name="AppTheme" parent="Base.AppTheme">
    <item name="searchViewStyle">@style/SearchViewTheme</item>
</style>
<style name="SearchViewTheme" parent="Widget.AppCompat.Light.SearchView">
    <item name="android:maxWidth">10000dp</item>
</style>

这是我的menu_main.xml

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_search"
        android:title="@string/action_search"
        android:orderInCategory="100"
        android:icon="@drawable/ic_action_search"
        app:showAsAction="collapseActionView|ifRoom"
        app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>

在菜单中试试这个:

<?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"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">

    <item
        android:id="@+id/action_search"
        android:title="@string/action_search"
        android:orderInCategory="100"
        android:icon="@drawable/ic_action_search"
        app:showAsAction="collapseActionView|ifRoom"
        app:actionLayout="@layout/searchview_layout"
    />

</menu>

采用这种布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.SearchView     
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/search_view_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/SearchViewTheme"/>

这种风格:

<style name="SearchViewTheme" parent="Widget.AppCompat.Light.SearchView">
    <item name="android:maxWidth">10000dp</item>
    <item name="android:textColorHint">@android:color/white</item>
</style>