Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a custom view in the ActionBar?

I am trying to display a custom view in the action bar. I am using SherlockActionBar. Here is my code. The custom view is never showing. What am I doing wrong?

View customNav = LayoutInflater.from(this).inflate(R.layout.my_layout, null);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setCustomView(customNav);
like image 598
Peter D. Avatar asked Dec 10 '12 14:12

Peter D.


People also ask

How to display custom view in Actionbar in Android?

This example demonstrates how to display custom view in ActionBar 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. Step 3 − Add the following code to res/layout/custom_action_bar.xml.

How do I add an action view to a toolbar?

To add an action view, create an <item> element in the toolbar's menu resource, as Add Action Buttons describes. Add one of the following two attributes to the <item> element: actionViewClass: The class of a widget that implements the action. actionLayout: A layout resource describing the action's components.

How do I add a custom action bar to an activity?

You must create an abstract BaseActivity and put the ActionBar code to an method inside that. You can extend your other 20 activity from BaseActivity instead of Activity. Then just call your method from all activity where you need the custom actionbar to work. Join Over 18,000+ Readers.

How do I configure the action of an action view?

When the user clicks an action view's icon, the view's UI fills the toolbar. If you need to configure the action, do so in your activity's onCreateOptionsMenu () callback. You can get the action view's object reference by calling the getActionView () method.


1 Answers

You must enable custom views first.

    getSupportActionBar().setDisplayShowCustomEnabled(true); // missing in your code
    getSupportActionBar().setCustomView(customNav);
like image 77
znat Avatar answered Sep 19 '22 18:09

znat