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

时间:2015-07-28 11:28:36

标签: android android-styles searchview

我已将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>

1 个答案:

答案 0 :(得分:8)

在菜单中尝试此操作:

<?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>