I was trying to create an action bar search in my application, but in the expanded state the SearchView is not taking the entire action bar width( it is still showing other actions)!
So, how to make the SearchView fill the full ActionBar Area (as in GMAIL app)?
This example demonstrate about how to create a custom action bar in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
Toolbar vs ActionBar The Toolbar is a generalization of the ActionBar system. The key differences that distinguish the Toolbar from the ActionBar include: Toolbar is a View included in a layout like any other View. As a regular View , the toolbar is easier to position, animate and control.
None of the above solutions worked for me. Setting the MaxWidth of the SearchView worked for me:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_search, menu);
SearchView searchView = (SearchView)menu.findItem(R.id.menu_search).getActionView();
searchView.setMaxWidth(Integer.MAX_VALUE);
Got it
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my_swipe_tabbed, menu);
MenuItem searchViewItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchViewItem.getActionView();
searchView.setIconifiedByDefault(false);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
searchView.setLayoutParams(params);
searchViewItem.expandActionView();
return true;
}
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MySwipeTabbedActivity" >
<item android:id="@+id/action_search"
android:title="Search"
android:icon="@android:drawable/ic_menu_search"
android:showAsAction="always|collapseActionView"
android:actionViewClass="android.widget.SearchView"
/>
<item android:id="@+id/action_share"
android:title="Share"
android:icon="@android:drawable/ic_menu_share"
android:showAsAction="ifRoom" />
<item android:id="@+id/action_settings"
android:title="Settings"
android:icon="@android:drawable/ic_menu_preferences"
android:showAsAction="never" />
</menu>
[Optional] Avoid the searchView from collapsing:
searchViewItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
return false; //never collapse
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With