这里介绍一下使用TabHost的第三种方法,特征是不继承TabActivity、并使用TabHost控件和多个布局文件。
这个例子实现的是点击不同的卡片进入不同的界面。
tab1.xml文件:
这个例子实现的是点击不同的卡片进入不同的界面。
整体思路:在xml文件中添加一个TabHost控件,在这个TabHost控件再添加一个LinearLayout布局,这个LinearLayout布局布局中放置一个TabWidget控件和一个FrameLayout布局,这个布局的宽和高都为填充父窗口,再新建两个xml文件,在这两个文件中都放入一个TextView控件;在活动中初始化这个TabHost容器,把新建的两个xml文件动态加载这个TabHost容器上。这样就实现了在手机屏幕上有两个菜单项,点击不同的菜单项,进入不同的页面。
activity_main.xml文件:
<TabHost
android:id="@+id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<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"
>
</FrameLayout>
</LinearLayout>
</TabHost>
tab1.xml文件:
<TextView
android:id="@+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="周杰伦"
/>
tab2.xml文件:
<TextView
android:id="@+id/textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="罗志祥"
/>
MainActivity.java文件:
TabHost th=(TabHost)findViewById(R.id.tabhost);
th.setup();
// 动态载入xml,而不需要activity
LayoutInflater layoutInflater=LayoutInflater.from(this);
layoutInflater.inflate(R.layout.tab1, th.getTabContentView());
layoutInflater.inflate(R.layout.tab2, th.getTabContentView());
th.addTab(th.newTabSpec("tab1").setIndicator("标签1").setContent(R.id.linearlayout1));
th.addTab(th.newTabSpec("tab2").setIndicator("标签2").setContent(R.id.linearlayout2));