在界面布局中定义TabHost组件
Activity继承TabActivity
调用TabActivity的getTabHost()方法获取TabHost
通过TabHost对象的方法来创建添加选项卡。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
>
<TabHost
android:layout_width="match_parent" android:layout_height="match_parent"
android:id="@android:id/tabhost"
android:layout_weight="1"
>
<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"></TabWidget>//代表选项卡的标签条。
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/tab01"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="消息"
android:textSize="30sp"
/>
</LinearLayout>
<LinearLayout
android:id="@+id/tab02"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="赛事"
android:textSize="30sp"
/>
</LinearLayout>
<LinearLayout
android:id="@+id/tab03"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="我的页面"
android:textSize="30sp"
/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>
注意:必须使用这样的,其他的id是错误的
android:id="@android:id/tabhost"
android:id="@android:id/tabs"
android:id="@android:id/tabcontent"
引用android系统已有的id
public class MainActivity extends TabActivity{ //Activity继承TabActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
//调用TabActivity的getTabHost()方法获取TabHost
TabHost tabHost=getTabHost();
TabHost.TabSpec tab1=tabHost.newTabSpec("tab1")
.setIndicator("赛事")
.setContent(R.id.tab01);
tabHost.addTab(tab1);
TabHost.TabSpec tab2=tabHost.newTabSpec("tab2")
.setIndicator("消息")
.setContent(R.id.tab02);
tabHost.addTab(tab2);
TabHost.TabSpec tab3=tabHost.newTabSpec("tab3")
.setIndicator("我")
.setContent(R.id.tab03);
tabHost.addTab(tab3);
}
}