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);
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.
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.
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.
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.
You must enable custom views first.
getSupportActionBar().setDisplayShowCustomEnabled(true); // missing in your code
getSupportActionBar().setCustomView(customNav);
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