带后退按钮的搜索视图

Searchview with back button

我正在实现没有操作栏和工具栏的搜索视图。一切都已修复,只剩下后退按钮。下面是我的 xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    <SearchView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:animateLayoutChanges="true"">
    </SearchView>
</RelativeLayout>

我得到了这样的东西。

下面是我需要的图片。

任何帮助都会很棒。

对于 API 21+ 你可以使用 android:searchIcon="[your drawable here]".

使用android.support.v7.widget.SearchView

Create a menu file like this in res/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">
    <item
        android:id="@+id/menu_search_album"
        android:icon="@drawable/ic_search"
        android:title="@string/str_search_album"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="collapseActionView|always" />

</menu>

Create a searchable.xml file like this in res/xml

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/search" >
</searchable>

now in your activity you need to Override onCreateOptionsMenu() method

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.my_menu, menu);

    MenuItem searchItem = menu.findItem(R.id.menu_search);
    SearchView searchView = (SearchView) searchItem.getActionView();

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String s) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String s) {
            return false;
        }
    });
    return true;
}

Now in your manifest file

    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <meta-data android:name="android.app.searchable"
            android:resource="@xml/searchable"/>

    </activity>

了解更多信息android.support.v7.widget.SearchView

同时勾选 How to create search interface