I am building a toolbar menu with a SearchView, an action view item, and other regular items.
I want the search icon to be always visible, so I use app:showAsAction="always"
.
I also had to use collapseActionView
, otherwise the search view would take the full width of the tool bar and push the other items, which is ugly.
Here is the complete XML of the menu:
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/search"
android:icon="@drawable/search"
android:title="@string/search"
app:actionViewClass="androidx.appcompat.widget.SearchView"
app:showAsAction="always|collapseActionView" />
<item
android:id="@+id/action"
android:icon="@drawable/edit_24"
android:title="@string/action"
app:showAsAction="ifRoom" />
<item
android:id="@+id/item1"
android:checkable="true"
android:title="@string/item1" />
<item
android:icon="@drawable/item2"
android:title="@string/item2" />
</menu>
Problem
Initially, everything seems to work fine.
The problem only occurs when I open the menu while the search view is expanded.
First weird thing: the action
item is still present as an action, but is also visible in the menu (see image). Then, when I’m done with the search view and I collapse it, the action item disappear from both the toolbar and the menu.
Images:
Before expand
After expand
After expand, menu open
After collapsed
After collapsed, menu open: It seems StackOverflow won’t let me add more than four images. This image would have shown that item “Action” no longer appears in the menu.
Workarounds
Setting app:showAsAction="always"
(instead of ifRoom
) for @+id/action
fixes the problem, but I don’t want to force the action to remain visible when the search view is expanded.
I have also tried to apply the solution of this question. I set an OnActionExpandListener
on the search view, and I call actionItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
when the search view is expanded, and invalidateOptionsMenu()
when it is collapsed. This works, but I still don’t understand what is wrong with the initial approach.