2
votes

I have followed the official HelloTabWidget Android tutorial and it works perfectly. Next I removed the tab icons and it still works perfectly. Now I would like to center the tabtext both horizontally and vertically in each tab, but I am clueless how. I've tried searching but couldn't find a solution.

I've tried adding android:layout_gravity to my main.xml file but it didn't help.

This is my onCreate main.java file:

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  TabHost tabHost = getTabHost();  // The activity TabHost
  TabHost.TabSpec spec;  // Resusable TabSpec for each tab
  Intent intent;  // Reusable Intent for each tab

  intent = new Intent().setClass(this, Indkobsliste.class);
  spec = tabHost.newTabSpec("tab1").setIndicator("Tab1")
                .setContent(intent);
  tabHost.addTab(spec);

  intent = new Intent().setClass(this, Opskrifter.class);
  spec = tabHost.newTabSpec("tab2").setIndicator("Tab2")
                .setContent(intent);
  tabHost.addTab(spec);

  intent = new Intent().setClass(this, Madplan.class);
  spec = tabHost.newTabSpec("tab3").setIndicator("Tab3")
                      .setContent(intent);
  tabHost.addTab(spec);

  tabHost.setCurrentTab(1);
}

This is the main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dp">
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="5dp"/>
    </LinearLayout>
</TabHost>

This is how my tabs look now: My tabs

1

1 Answers

1
votes

If you are running Android API Level >= 4, you can use TabHost.TabSpec.setIndicator(View view). This allows you to specify any view, so just provide one where you vertically center your text.

If, however, you are running a lower API level, try using the answer from this other stackoverflow question. It suggests using reflection to set the view even though the API does not publish the required setIndicator method.