How to display custom view in ActionBar?
This is how it worked for me (from above answers it was showing both default title and my custom view also).
ActionBar.LayoutParams layout = new ActionBar.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
// actionBar.setCustomView(view); //last view item must set to android:layout_alignParentRight="true" if few views are there
actionBar.setCustomView(view, layout); // layout param width=fill/match parent
actionBar.setDisplayShowCustomEnabled(true);//must other wise its not showing custom view.
What I noticed is that both setCustomView(view)
and setCustomView(view,params)
the view width=match/fill parent. setDisplayShowCustomEnabled (boolean showCustom)
There is a trick for this. All you have to do is to use RelativeLayout
instead of LinearLayout
as the main container. It's important to have android:layout_gravity="fill_horizontal"
set for it. That should do it.
I struggled with this myself, and tried Tomik's answer. However, this didn't made the layout to full available width on start, only when you add something to the view.
You'll need to set the LayoutParams.FILL_PARENT
when adding the view:
//I'm using actionbarsherlock, but it's the same.
LayoutParams layout = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
getSupportActionBar().setCustomView(overlay, layout);
This way it completely fills the available space. (You may need to use Tomik's solution too).
The answers from Tomik and Peterdk work when you want your custom view to occupy the entire action bar, even hiding the native title.
But if you want your custom view to live side-by-side with the title (and fill all remaining space after the title is displayed), then may I refer you to the excellent answer from user Android-Developer here:
https://stackoverflow.com/a/16517395/614880
His code at bottom worked perfectly for me.