How to display custom view in ActionBar? How to display custom view in ActionBar? android android

How to display custom view in ActionBar?


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).


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 parentactionBar.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)