FragmentTabHost with horizontal scroll

Based on my experience, the FragmentTabHost doesn’t care much about the xml definitions, things must be made programmatically. I got it working by leaving out the HorizontalScrollView from the xml and adding it in my onCreate for the FragmentActivity.

The xml:

<android.support.v4.app.FragmentTabHost xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="0" />

        <FrameLayout
            android:id="@+id/realtabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>

</android.support.v4.app.FragmentTabHost>

Then in the onCreate after adding the tabs (also programmatically):

TabWidget tw = (TabWidget) findViewById(android.R.id.tabs);
LinearLayout ll = (LinearLayout) tw.getParent();
HorizontalScrollView hs = new HorizontalScrollView(this);
hs.setLayoutParams(new FrameLayout.LayoutParams(
    FrameLayout.LayoutParams.MATCH_PARENT,
    FrameLayout.LayoutParams.WRAP_CONTENT));
ll.addView(hs, 0);
ll.removeView(tw);
hs.addView(tw);
hs.setHorizontalScrollBarEnabled(false);

Don’t know if this is the most elegant solution but it seems to work OK.

Leave a Comment