Search code examples
androidandroid-actionbarsearchviewandroid-optionsmenu

How to prevent ActionBar SearchView button from disappearing


I have been having a lot of trouble trying to fix this one and couldn't find any solutions for this anywhere.

Currently I have the following ActionBar option 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/action_search"
        android:icon="@drawable/ic_search"
        android:title="@string/menu_search"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="ifRoom|collapseActionView" />

    <item
        android:id="@+id/action_sort_by"
        android:title="@string/sort_by"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_refresh"
        android:title="@string/action_refresh"
        app:showAsAction="never" />

</menu>

And everything works perfectly fine except if the options menu is opened while the search option is also opened:

The target layout as expected

enter image description here

The search option opened

enter image description here

This is the step that causes the problem, as you can see the Search option is now in the menu

enter image description here

Because of the previous step the search button is gone when closing the menu and the search option

enter image description here

If I don't open the options menu while the search option is also opened then everything works perfectly well, however this is something that cannot be expected for users to do and they might open the menu with the search options opened, leading to the search icon to disappear, resulting in a very problematic user experience.

How can I fix this, how can I prevent this problem from happening while keeping that same layout? Search icon visible, everything else in the 3 dots options menu.


Solution

  • To always show the search icon, simple change app:showAsAction="ifRoom|collapseActionView" to app:showAsAction="always|collapseActionView"