Android Actionbar set width to the tabs

Mattias te Wierik picture Mattias te Wierik · May 16, 2013 · Viewed 7.1k times · Source

Currently I'm busy on a WHMCS app for my company. As navigation I want to use the Tab functionality in the actionbar.

However, how can you edit the width of a tab? I need 5 together on one screen without the need to scroll. I already tried it with some styles like this:

<style name="AppBaseTheme" parent="android:Theme.Light">
</style>

<style name="AppTheme" parent="AppBaseTheme">
    <item name="@android:attr/actionBarTabStyle">@style/tab_nav</item>
    <item name="android:actionBarTabTextStyle">@style/actionBarTabTextStyle</item>
</style>

<style name="actionBarTabTextStyle" parent="android:Widget.Holo.Light.ActionBar.TabText.Inverse">
    <item name="android:padding">1dp</item>
</style>

<style name="tab_nav" parent="android:style/Widget.Holo.Light.Tab">
 <item name="android:paddingLeft">-25dp</item>
</style> 

<style name="CustomTabTextStyle" parent="@android:style/TextAppearance.Holo">
    <item name="android:textColor">#2456c2</item>
</style>

However, the width won't shrimp when using a higher negative value.

Answer

Areeb Gillani picture Areeb Gillani · Jul 27, 2013

Hi i think this may help you... This code is actually making the actionbar bound to the screen width, so the tabs will adjust by themselves =)

private void setTabsMaxWidth() {
   DisplayMetrics displaymetrics = new DisplayMetrics();
   getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
   int screenWidth = displaymetrics.widthPixels;
   final ActionBar actionBar = getActionBar();
   final View tabView = actionBar.getTabAt(0).getCustomView();
   final View tabContainerView = (View) tabView.getParent();
   final int tabPadding = tabContainerView.getPaddingLeft() + tabContainerView.getPaddingRight();
   final int tabs = actionBar.getTabCount();
   for(int i=0 ; i < tabs ; i++) {
      View tab = actionBar.getTabAt(i).getCustomView();
      TextView text1 = (TextView) tab.findViewById(R.id.text1);
      text1.setMaxWidth(screenWidth/tabs-tabPadding-1);
  }
}