How can I get back button working when searchview in Android

android, searchview

Solution

When searchView is open and back button is pressed you expect to see the searchView closed (aka setIconified(true)) This is a standar behaviour as per google apps searchview implementation.

So all you need to do is something like that

    mSearchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                mSearchView.setIconified(true);
            }
        }
    });

Problem

I've been searching for more than 4 hours all over the internet how to get the back button working properly when searchview is opened but I just can't achieve it. Here is my searchview. ``` searchview = (SearchView) findViewById(R.id.searchView); searchview.setOnClickListener(this); @Override public void onClick(View v) { if (v.getId() == R.id.searchView){ //Cursor cursor = manager.obtenerIDColumnaServicio(searchview.getQuery().toString()); adapterOfDataBase.changeCursor(cursor); } } ``` Here is the xml: ``` <SearchView android:layout_width="match_parent" android:layout_height="63dp" android:id="@+id/searchView" android:iconifiedByDefault="true" android:backgroundTint="#ff000000" android:layout_marginRight="0dp" /> ``` All this withing a huge class using SQL and some methods to insert, delete, etc etc tables & entries. So my problem is that everytime I click on the searchview it expands in order to write the text, everyting ok, but when I push back button from android nothing happens. I tried 2 options but none worked, if you could just help me.... ``` @Override public boolean onKeyDown(int keyCode, KeyEvent event) { //MEJORAR ESTO if (keyCode == KeyEvent.KEYCODE_BACK) { searchview.onActionViewCollapsed(); return true; } return super.onKeyDown(keyCode, event); } //None of this 2 methods are working. I tried them separately @Override public void onBackPressed(){ if (!this.searchview.isIconified()) { this.searchview.setIconified(true); } else { super.onBackPressed(); } } ```

Original source

Related problems