How to center text in tabhost?

Miroufle picture Miroufle · Sep 18, 2011 · Viewed 6.9k times · Source

I have a basic question. In many tabhost examples, we find tabs with image and text.

In my case, I would like to only display a text, but the issue is that my text is horizontally centered but not vertically (The text is at the bottom of my tab).

I tried : android:layout_gravity="center" in the framelayout, but it doesn't work.

Do you have any idea, please ?

My xml.

<TabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center">

    <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center">

        <TabWidget android:id="@android:id/tabs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:layout_gravity="center"/>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center">

        </FrameLayout>

    </LinearLayout>

</TabHost>

solved : I customized my tabs thanks to the following tutorial : http://joshclemm.com/blog/?p=136

Thank you

Answer

udai picture udai · Feb 15, 2015
  1. Try to get the tab titles first and set gravity and layouts explicitly as shown below:

    TextView textView = (TextView)tabHost.getTabWidget().getChildAt(0)
    .findViewById(android.R.id.title);
    textView.setGravity(Gravity.CENTER);        
    textView.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
    textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
    

    Hope this help.