My search view is stuck on the right side replacing the toolbar's title when collapsed.

Before Opening: Before opening the search view After Closing: After opening and closing the search view

Menu File:

<?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_white_24dp"
      android:title="@android:string/search_go"
      app:actionLayout="@layout/full_width_search_view"
      app:actionViewClass="android.widget.SearchView"
      app:showAsAction="collapseActionView|ifRoom"/>

  <item
      android:id="@+id/btn_create"
      android:icon="@drawable/ic_add_white_24dp"
      android:title="@string/create"
      app:showAsAction="collapseActionView|ifRoom"/>

  <item
      android:id="@+id/btn_delete"
      android:icon="@drawable/ic_delete_white_24dp"
      android:title="@string/remove"
      app:showAsAction="collapseActionView|ifRoom"/>
</menu>

Full-Width Search View (which obviously is not working...):

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

Activity's Code:

override fun onCreateOptionsMenu(menu: Menu): Boolean {
  menuInflater.inflate(R.menu.search_create_delete, menu)

  // Handle Searching
  val searchView: SearchView = menu.findItem(R.id.search).actionView as SearchView
  searchView.isIconified = false
  searchView.clearFocus()

  menu.findItem(R.id.btn_delete).isVisible = orderLine.hasCustomer()

  return super.onCreateOptionsMenu(menu)
}

Any help is appreciated. Thanks in advance!

1 Answers 11

You have to override the onBackPressed() method because you can collapse the SearchView by pressing the back button or back button in ActionBar

If you press the back button then:

override fun onBackPressed() {
    if (!searchView.isIconified) {
        searchView.isIconified == true;
    } else {
        super.onBackPressed();
    }
}

If you press the ActionBar back button then you have to override the onOptionsItemSelected() method and then you have to do it in the same way given above.

Not the answer you're looking for? Browse other questions tagged or ask your own question.