Text input in SearchView doesn't show

白昼怎懂夜的黑 提交于 2019-12-01 15:57:24

I had the same issue, and for me it was because I had set my toolbar height to wrap_content. Try giving it a size, like this:

<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:theme="@style/ToolbarTheme"
    app:popupTheme="@style/AppTheme.PopupOverlay"
    app:layout_scrollFlags="scroll|enterAlways"
    />

This is the code I use for my recent project and it's work fine:

First define search_menu.xml (make sure use android supportV7) :

<?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/search"
        android:icon="@drawable/ic_search_gray"
        android:title="@string/action_search"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="always" />
</menu>

Then define in your onCreateOptionMenu of your Activity:

MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_search, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.search));
searchView.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(getApplicationContext(), SearchActivity.class)));
searchView.setMaxWidth(Integer.MAX_VALUE);
MenuItemCompat.expandActionView(menu.findItem(R.id.search));
searchView.setIconifiedByDefault(true);
searchView.setIconified(false);

Also my Toolbar:

<android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/gray_lightest"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:contentInsetStartWithNavigation="0dp" />

Add meta-data to your AndroidManifest.xml:

    <activity
        android:name=".ui.activity.SearchActivity"
        android:launchMode="singleTop">
        <intent-filter>
            <action android:name="android.intent.action.SEARCH" />
        </intent-filter>
        <meta-data
            android:name="android.app.searchable"
            android:resource="@xml/searchable"
            android:value=".ui.activity.SearchActivity" />
    </activity>

Final result:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!