How to customize actionbar items

I just wanted to point out this really handy method that lets you specify your own layout for an action item.

<strong>android:actionlayout=”@layout/action_layout”</strong>

Super cool albeit a bit obscure!

This is all you need to do:

In your menu xml:

<item android:id="@+id/menu_item"
android:showAsAction="always|withText"
android:actionLayout="@layout/action_layout"
android:title="@string/menu_settings"/>

It’s that simple!

Your layout can be anything! in my case i just tried it out with a button.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".CacheTestActivity" >
<ImageButton
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:contentDescription="Custom button!"
android:scaleType="fitCenter"
android:src="@drawable/logo" />
</LinearLayout>

This really makes it simple to customize your actionbar action items!
Hope this helps!

2 comments on “How to customize actionbar items”

  1. suomi35

    How do you then get a reference to those custom items?
    For example, if I use your example and want to setText() on the button, how do I access the button from a fragment?

    Thanks

  2. suomi35

    Seems that I was trying to reference the items too early in the lifecycle. I moved my calls a bit later and got it to work. Thanks for a cool tip!

Leave a Reply

Your email address will not be published. Required fields are marked *