Android TabHost未显示在屏幕中
我试图在我的应用程序上使用Android TabHost未显示在屏幕中,android,layout,android-tabhost,Android,Layout,Android Tabhost,我试图在我的应用程序上使用TabHost,我只是用设计将它拖到我的活动中,但当我运行它时,它就不会出现,只会出现白色屏幕,有人知道为什么吗 <TabHost android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/tabHost" android:layout_gravity="center_horizontal"> &
TabHost
,我只是用设计将它拖到我的活动中,但当我运行它时,它就不会出现,只会出现白色屏幕,有人知道为什么吗
<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>
发生这种情况的原因很简单,因为您无法仅使用XML代码创建
TabHost
。您需要将TabSpec
s添加到TabHost
中,如下所示:
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);
“setContent(newintent(this,TabActivity2.class))方法用于什么?我也是这样做的,但是应用程序抛出了一个NullPointerException,所以我最终将其替换为setContent(R.id.yourTabId);在本例中,我将活动放在选项卡中,因此您需要在项目中创建
TabActivity1,2,3
。您忘记了tabHost.setup()(在我的案例中有一个例外)