首先在布局文件中配置几个TextView,作为某个Tab的内容来显示:
tab_demo.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/tab_view1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="tab_view1"
/>
<TextView
android:id="@+id/tab_view2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="tab_view2"
/>
<TextView
android:id="@+id/tab_view3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="tab_view3"
/>
</FrameLayout>
Java代码,注意这里继承的不是Activity而是TabActivity:
//这里继承的是TabActivity
public class TestTab extends TabActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
TabHost tabHost = getTabHost();
// LayoutInflater:This class is used to instantiate layout XML file into
// its corresponding View objects
// from:Obtains the LayoutInflater from the given context.
LayoutInflater.from(this).inflate(R.layout.tab_demo,
tabHost.getTabContentView(), true);
// newTabSpec:tab的标识,setIndicator:设置tab的显示名称 tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("tab1")
.setContent(R.id.tab_view1));
tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("tab2")
.setContent(R.id.tab_view2));
tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("tab3")
.setContent(R.id.tab_view3));
}
}