Skip to content Skip to sidebar Skip to footer

Expand Search View To Use Entire Action Bar (hide Other Things)

I have a SearchView inside my ActionBar, and I want to use the entire ActionBar when the search icon is pressed, but I can only use the ActionBar free space eg.: http://imgur.com/w

Solution 1:

Well you could imitate that yourself by hiding all the other items when the SearchView is expanded:

@OverridepublicbooleanonCreateOptionsMenu(final Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);

    finalMenuItemsearchItem= menu.findItem(R.id.search);
    SearchViewsearchView= (android.widget.SearchView) searchItem.getActionView();

    // Detect SearchView icon clicks
    searchView.setOnSearchClickListener(newView.OnClickListener() {
        @OverridepublicvoidonClick(View v) {
            setItemsVisibility(menu, searchItem, false);
        }
    });
    // Detect SearchView close
    searchView.setOnCloseListener(newSearchView.OnCloseListener() {
        @OverridepublicbooleanonClose() {
            setItemsVisibility(menu, searchItem, true);
            returnfalse;
        }
    });

    returnsuper.onCreateOptionsMenu(menu);
}

privatevoidsetItemsVisibility(Menu menu, MenuItem exception, boolean visible) {
    for (int i=0; i<menu.size(); ++i) {
        MenuItemitem= menu.getItem(i);
        if (item != exception) item.setVisible(visible);
    }
}

Solution 2:

This would be a late answer but you could add this attribute to your menu item and the work is done for you.

app:showAsAction="collapseActionView|always"

Keyword here being the collapseActionView.

Solution 3:

I tried this line of code to make the searchview expand the full width available. This works when there are other items shown in the actionbar either.

searchView.setMaxWidth(android.R.attr.width);

Solution 4:

"collapseActionView" attribute works for menu item in menu.xml to hide other things and add back action button-

 <item
    android:id="@+id/action_search"
    android:icon="@drawable/ic_search"
    android:title="@string/search"
    app:actionViewClass="androidx.appcompat.widget.SearchView"
    app:showAsAction="always|collapseActionView" />

In few case if it doesn't work, we can explicitly hide/show other menu items by using MenuItem.OnActionExpandListener as below-

        action_search.setOnActionExpandListener(newMenuItem.OnActionExpandListener() {
        @OverridepublicbooleanonMenuItemActionExpand(MenuItem item) {
            action_setting.setVisible(false); // to hide itemreturntrue;
        }

        @OverridepublicbooleanonMenuItemActionCollapse(MenuItem item) {
            action_setting.setVisible(true); // to show itemreturntrue;
        }
    });

Post a Comment for "Expand Search View To Use Entire Action Bar (hide Other Things)"