首先简单的创建一个Tab有以下步骤:
1、在布局文件中使用FramLayout列出Tab组件及Tab中的内容组件。
2、Activity要继承TabActivity。
3、调用TabActivity的getTabHost()方法获得TabHost对象。
4、通过TabHost创建Tab选项。
以下是创建过程:
1、创建activity_main.xml文件
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="文本1" />
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="文本2" />
<TextView
android:id="@+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="文本3" />
</FrameLayout>
<FrameLayout>改为<TabHost>也行
2、继承TabActivity
public class MainActivity extends TabActivity
3、获取TabHost对象
TabHost th = getTabHost();
LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main,th.getTabContentView(), true);//设置使用TabHost布局
获取了TabHost对象之后,设置了布局,故不能再调用setContentView设置了
4、通过TabHost创建Tab选项
th.addTab(th.newTabSpec("123").setIndicator("one").setContent(R.id.text1));
th.addTab(th.newTabSpec("456").setIndicator("two").setContent(R.id.text2));
th.addTab(th.newTabSpec("789").setIndicator("three").setContent(R.id.text3));
若想在创建Tab选项的时候同时显示文字和图标,可以这样创建Tab:
th.addTab(th.newTabSpec("123").setIndicator("one",getResources().getDrawable(R.drawable.ic_launcher)).setContent(R.id.text1));