創建一個項目。Tab繼承自TabActivity.
main.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"> <!-- 第一個Tab 對應的布局 --> <TextView android:id="@+id/tab1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="tab1"/> <!-- 第二個Tab 對應的布局 --> <TextView android:id="@+id/tab2" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="tab2"/> <!-- 第三個Tab 對應的布局 --> <TextView android:id="@+id/tab3" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="tab3"/> </FrameLayout>
Tab.class
package com.example.Tab; import android.app.TabActivity; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.widget.TabHost; import android.widget.Toast; public class Tab extends TabActivity { private TabHost tabHost; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //從TabActivity上面獲取放置Tab的TabHost tabHost = getTabHost(); //from(this)從這個TabActivity獲取LayoutInflater //R.layout.main 存放Tab布局 //通過TabHost獲得存放Tab標簽頁內容的FrameLayout //是否將inflate 拴系到根布局元素上 LayoutInflater.from(this).inflate(R.layout.main, tabHost.getTabContentView(), true); //設置TabHost的顏色 tabHost.setBackgroundColor(Color.argb(150, 150, 150, 150)); //制造一個新的標簽tab1,這個名字就是onTabChanged中的參數s //設置一下顯示的標題為Tab_1,設置一下標簽圖標 //設置一下該標簽頁的布局內容為R.id.tab1,這是FrameLayout中的一個子Layout tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Tab_1", getResources().getDrawable(R.drawable.icon)) .setContent(R.id.tab1)); tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("Tab_2", getResources().getDrawable(R.drawable.icon)) .setContent(R.id.tab2)); tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("Tab_3", getResources().getDrawable(R.drawable.icon)) .setContent(R.id.tab3)); //設置標簽切換動作 tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() { @Override public void onTabChanged(String s) { Toast.makeText(Tab.this, "Tab Change to " + s, Toast.LENGTH_LONG).show(); } }); setContentView(tabHost); } }
效果:
參考: