Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force collapse of tabs in ActionBar

I'm developing a Android application, using the ActionBarSherlock library. In one activity, I use a tabbed navigation in combination with a collapsed ActionBar (action items at the bottom).

In this picture you can see the Activity in its current state: The tabs are being pushed in a second row.

Current ActionBar


In the following picture you can see the Activity the way I want it to be: The tabs should be in the top row, not in a second row. I already read the ActionBar and ActionBarSherlock documentation, but found no way to force this behaviour.

The wished ActionBar layout

This is the current code, used to create the ActionBar.

public class AdminActivity extends SherlockFragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_admin);

    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    ActionBar.Tab itemsTab = actionBar.newTab().setText(R.string.label_tab_items);
    ActionBar.Tab usersTab = actionBar.newTab().setText(R.string.label_tab_users);

    actionBar.addTab(itemsTab);
    actionBar.addTab(usersTab);
}

Any ideas?

like image 294
damaxxed Avatar asked Jul 14 '12 14:07

damaxxed


1 Answers

There is a reflection 'hack' to do this. I take no credit for the solution, which I found in this StackOverflow question replicate ActionBar Tab(s) with custom view.

//pre-ICS
if (actionBarSherlock instanceof ActionBarImpl) {
    enableEmbeddedTabs(actionBarSherlock);

//ICS and forward
} else if (actionBarSherlock instanceof ActionBarWrapper) {
    try {
        Field actionBarField = actionBarSherlock.getClass().getDeclaredField("mActionBar");
        actionBarField.setAccessible(true);
        enableEmbeddedTabs(actionBarField.get(actionBarSherlock));
    } catch (Exception e) {
        Log.e(TAG, "Error enabling embedded tabs", e);
    }
} 

//helper method
private void enableEmbeddedTabs(Object actionBar) {
    try {
        Method setHasEmbeddedTabsMethod = actionBar.getClass().getDeclaredMethod("setHasEmbeddedTabs", boolean.class);
        setHasEmbeddedTabsMethod.setAccessible(true);
        setHasEmbeddedTabsMethod.invoke(actionBar, true);
    } catch (Exception e) {
        Log.e(TAG, "Error marking actionbar embedded", e);
    }
}

See also this blog post: http://sparetimedev.blogspot.co.uk/2012/11/forcing-embedded-tabs-in-actionbar.html

like image 135
Andy Avatar answered Nov 03 '22 07:11

Andy