Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a layout with tabs completely in XML?

I'm trying to make tabs in a layout. I've found a lot of examples and tutorials using TabWidget, TabHost, but they all involve one of the following:

  • Java code in the activity
  • Separate activities for each tabs
  • Separate fragments for each tabs

The content inside the tabs is static, so I should just be able to include everything in the layout, in pure XML.

Anyway to do that?

like image 360
erwan Avatar asked Mar 14 '13 20:03

erwan


1 Answers

The simple answer, no. You have to setup your TabHost in Java code and create your tabs. You can have static layouts for the tabs without using fragments but it still requires setup in Java.

If you don't do this setup in code, your TabWidget won't know which layout corresponds to which tab and wouldn't be able to function. You're going to have to write a bit of code.

The code for doing this is really simple though.

The XML (placed inside your layout where you want it):

<TabHost android:id="@+id/tab_host"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TabWidget android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <FrameLayout android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
            <LinearLayout
                android:id="@+id/tab_one_container"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
            <LinearLayout
                android:id="@+id/tab_two_container"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
        </FrameLayout>
    </LinearLayout>
</TabHost>

The Java code (placed wherever you setup your layout):

TabHost host = (TabHost)findViewById(R.id.tab_host);
host.setup();

TabSpec spec = host.newTabSpec("Tab One");
spec.setContent(R.id.tab_one_container);
spec.setIndicator("Tab One");
host.addTab(spec);

spec = host.newTabSpec("Tab Two");
spec.setContent(R.id.tab_two_container);
spec.setIndicator("Tab Two");
host.addTab(spec);
like image 186
Michael Celey Avatar answered Sep 30 '22 19:09

Michael Celey