Search code examples
androidandroid-layoutsearchview

Searchview with back button


I'm implementing searchview without Actionbar and toolbar. Everything is fixed, just back button remains. Below is my 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>

I got something like this.

enter image description here

Below is the image what I need.

enter image description here

Any help would be great.


Solution

  • Use 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

    enter image description here

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

    for more information android.support.v7.widget.SearchView

    Also check How to create search interface