6

I'm trying to use TabHost on my app, and I simply dragged it to my activity using the design, but when I run it, it just won't appear, just get the white screen, does anyone knows why?

<TabHost
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tabHost"
    android:layout_gravity="center_horizontal">

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

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

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

            <LinearLayout
                android:id="@+id/tab1"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical"></LinearLayout>

            <LinearLayout
                android:id="@+id/tab2"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical"></LinearLayout>

            <LinearLayout
                android:id="@+id/tab3"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical"></LinearLayout>
        </FrameLayout>
    </LinearLayout>
</TabHost>

SMR
  • 6,628
  • 2
  • 35
  • 56
Bruno Braga
  • 570
  • 2
  • 4
  • 13

1 Answers1

10

This is happening simply because you just can't create TabHost using only XML code . You need to add TabSpecs to the TabHost like this:

TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);

TabSpec tab1 = tabHost.newTabSpec("First Tab");
TabSpec tab2 = tabHost.newTabSpec("Second Tab");
TabSpec tab3 = tabHost.newTabSpec("Third Tab");

tab1.setIndicator("Tab1");
tab1.setContent(new Intent(this,TabActivity1.class));

tab2.setIndicator("Tab2");
tab2.setContent(new Intent(this,TabActivity2.class));

tab3.setIndicator("Tab3");
tab3.setContent(new Intent(this,TabActivity3.class));

tabHost.addTab(tab1);
tabHost.addTab(tab2);
tabHost.addTab(tab3);
SMR
  • 6,628
  • 2
  • 35
  • 56
  • 1
    What is the "setContent(new Intent(this,TabActivity2.class))" method used for? I was doing it the same way but the app was throwing a NullPointerException, so I ended up replacing it to setContent(R.id.yourTabId); – Sandoval0992 May 18 '17 at 18:09
  • in this example I am putting activity in the tabs so you will need to create `TabActivity1,2,3` in your project – SMR May 22 '17 at 05:58
  • You forgot tabHost.setup() (there was an exception in my case) – maracuja-juice Nov 01 '17 at 16:15