我刚刚开发了一个标签应用程序,并使用以下函数在代码中创建标签。该函数使用intent,这意味着每当选择一个选项卡时,都会使用intent在选项卡主体中加载一个活动。此函数在主活动中调用。
private void SetupTabs()
{
TabHost tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;
//*****************************
intent = new Intent().setClass(MPaper.this, NewsList.class);
spec = tabHost.newTabSpec(NewsTag).setIndicator("News")
.setContent(intent);
tabHost.addTab(spec);
//*****************************
intent = new Intent().setClass(MPaper.this, Search.class);
spec = tabHost.newTabSpec(SearchTag).setIndicator("Search")
.setContent(intent);
tabHost.addTab(spec);
//****************************
intent = new Intent().setClass(MPaper.this, MyNewsList.class);
spec = tabHost.newTabSpec(MyNewsTag).setIndicator("My News")
.setContent(intent);
tabHost.addTab(spec);
//*****************************
intent = new Intent().setClass(MPaper.this, Extras.class);
spec = tabHost.newTabSpec(ExtrasTag).setIndicator("Extras")
.setContent(intent);
tabHost.addTab(spec);
//*****************************
tabHost.setCurrentTabByTag(NewsTag);
}
“新闻列表”活动中的列表视图由XML生成,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="@+id/NewsList"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
针对Fabios的以下评论:
是的,请使用visibility属性或尝试使用下面提到的方法实现选项卡:
private void TabSetup()
{
tabs = (TabHost)findViewById(R.id.tabhost);
tabs.setup();
TabHost.TabSpec spec = tabs.newTabSpec("MainNewsTag");
spec.setContent(R.id.MainNews);
spec.setIndicator("Home");
tabs.addTab(spec);
spec = tabs.newTabSpec("SearchTag");
spec.setContent(R.id.Search);
spec.setIndicator("Search");
tabs.addTab(spec);
spec = tabs.newTabSpec("MyNewsTag");
spec.setContent(R.id.MyNews);
spec.setIndicator("My News");
tabs.addTab(spec);
spec = tabs.newTabSpec("ExtrasTag");
spec.setContent(R.id.MyNews);
spec.setIndicator("Extras");
tabs.addTab(spec);
}
其中as布局文件如下:
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tabhost" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout android:layout_height="fill_parent"
android:layout_width="fill_parent">
<TableLayout android:layout_height="fill_parent"
android:layout_width="fill_parent">
<TabWidget android:id="@android:id/tabs"
android:layout_height="wrap_content"
android:layout_width="fill_parent" />
<FrameLayout android:id="@android:id/tabcontent"
android:layout_height="wrap_content"
android:layout_width="fill_parent" >
<ListView android:id="@+id/MainNews"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</ListView>
.... and so on