, , ,

Hurray! Firefox for Android is here! Now it’s time to reveal some Android hacks that went into making the awesomest browser.

Android introduced the ActionBar feature starting Honeycomb (Thanks Matias Duarte!). This is now pretty standard feature in phones running Ice Cream Sandwich and JellyBean too. However pre-Honeycomb devices cannot show this. To address this, there are libraries like ActionBarSherlock, that helps in providing a similar experience on pre-honeycomb devices.

However, if the ActionBar had a totally custom UI, like Firefox, such libraries wouldn’t be able to tackle them. Also, it’s better to write 10 lines of code, instead of shipping a product with an external library, just for the sake of parity in pre-Honeycomb devices. Sp, how can we bring in ActionBar like feature on pre-honeycomb and use ActionBar on honeycomb+ devices? Let’s take a simple example.


Clearly the screen has two portions: A title and a content portion. Almost every app, say Instagram, Facebook, Foursquare have this pattern. Let’s have two XMLs, title.xml and content.xml, to represent the same.

In case of pre-Honeycomb devices, the two layouts are combined into the activity.xml. This can be achieved using an tag.

<!-- layout/activity.xml -->
<LinearLayout android:layout_width="fill_parent"

    <include layout="@layout/title"/>

    <include layout="@layout/content"/>


In case of Honeycomb+ devices, the title will be supported by the ActionBar. Hence the activity.xml is left with just the content portion.

<!-- layout-v11/activity.xml -->
<LinearLayout android:layout_width="fill_parent"

    <include layout="@layout/content"/>


To specify the custom ActionBar, it’s better to use XML. Android loads the ActionBar even before the onCreate()is called for the activity. The styles are specified to the actionBarStyle attribute in the themes for the activity.

<!-- values-v11/themes.xml -->
<style name="MyActivityTheme" parent="@android:style/Theme.Holo">
     <item name="android:actionBarStyle">@style/ActionBar.MyActivity</item>
<!-- values-v11/styles.xml -->
<style name="ActionBar" parent="android:style/Widget.Holo.ActionBar" />

<style name="ActionBar.MyActivity">
    <item name="android:displayOptions">showCustom</item>
    <item name="android:customNavigationLayout">@layout/title</item>

Now that the layouts are ready, referring to the ActionBar is pretty simple. In onCreate(), the title view is obtained as follows.

View actionBar;
if (Build.VERSION.SDK_INT >= 11) {
    actionBar = getActionBar().getCustomView();
} else {
    actionBar = findViewById(R.id.title);

From this point, it’s just a matter of using actionBar as needed (or leave it as it is).