TabHost基本实现
一、简介TabHost(选项卡)
TabHost即,盛放Tab的容器,实现TabHost基本有两种方式。
方式一:继承TabActivity,从TabActivity中,用getTabHost()方法,获得TabHost对象。各个Tab中的内容在在TabHost标签中定义即可。参考:http://www.cnblogs.com/devinzhang/archive/2012/01/18/2325887.html
方式二:不继承TabActivity,直接在xml文件中使用<TabHost>标签定义,但是TabWidget(选项卡界面)d必须是@android:id/tabs,FrameLayout的id必须是@android:id/tabcontent。
以下重点阐述第二种方式。
二、例子
不继承TabActivity
activity_main.xml文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<!-- TabHost必须包含一个 TabWidget和一个FrameLayout-->
<TabHost android:id="@+id/tabhost"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- TabWidget的id属性必须为 @android:id/tabs-->
<TabWidget
android:id="@android:id/tabs"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<!-- FrameLayout的id属性必须为 @android:id/tabcontent-->
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/view1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="11111"/>
<TextView android:id="@+id/view2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="22222"/>
<TextView android:id="@+id/view3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="33333"/>
</FrameLayout>
</LinearLayout>
</TabHost>
</RelativeLayout>
MainActivity.java文件
package com.example.mytabhost;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TabHost;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取TabHost对象
TabHost tabHost = (TabHost) findViewById(R.id.tabhost);
// 如果没有继承TabActivity时,通过该种方法加载启动tabHost
tabHost.setup();
/**
* 在tabHost中创建一个Tab标签:
*
* myTabhost
.addTab(myTabhost.newTabSpec("TT")// 制造一个新的标签TT
.setIndicator("KK",
getResources().getDrawable(R.drawable.ajjc))
// 设置一下显示的标题为KK,设置一下标签图标为ajjc
.setContent(R.id.widget_layout_red));//设置一下该标签页的布局内容为R.id.widget_layout_red
*/
tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("第一个标签",
getResources().getDrawable(R.drawable.ic_launcher)).setContent(
R.id.view1));
tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("第三个标签")
.setContent(R.id.view3));
tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("第二个标签")
.setContent(R.id.view2));
}
}
运行效果: