標籤頁在顯示上是相當方便且用途廣泛的元件,在電話簿,訊息中常常可見,簡單的範例如下圖
首先是 TabHost 和 TabWidget 的關係, TabHost 包含著 TabWidget , 可以有多個 TabWidget 的存在,如上圖就包含 4 個 TabWidget (消費清單,本日消費,本周消費,本月消費),每個 TabWidget 可以視為不同的 Activity ,當手指觸碰到不同的 TabWidget ,就會執行不同的 TabWidget, TabHost 的 xml 結構如下
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
</TabHost>
這是標準的 TabHost 的 xml 格式,第 7 行指出是個線性垂直的佈局,且依序為 TabWidget(標籤頁),以及其內容(FrameLayout),接著來看 TabHost的程式碼,如下
package com.example.helloworld;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
@SuppressWarnings("deprecation")
public class Table_Flow extends TabActivity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.table_host);
initView();
}
void initView(){
TabHost thost = getTabHost();// build tabhost
Intent inte = new Intent();
inte.setClass(Table_Flow.this, Table_widget4.class);
TabSpec ts = thost.newTabSpec("tab4");
ts.setContent(inte);
ts.setIndicator("消費清單");
thost.addTab(ts);
inte = new Intent();
inte.setClass(Table_Flow.this, Table_widget1.class);
TabSpec ts1 = thost.newTabSpec("tab1");
ts1.setContent(inte);
ts1.setIndicator("本日消費");
thost.addTab(ts1);
inte = new Intent();
inte.setClass(Table_Flow.this, Table_widget2.class);
TabSpec ts2 = thost.newTabSpec("tab2");
ts2.setContent(inte);
ts2.setIndicator("本周消費");
thost.addTab(ts2);
inte = new Intent();
inte.setClass(Table_Flow.this, Table_widget2.class);
TabSpec ts3 = thost.newTabSpec("tab3");
ts3.setContent(inte);
ts3.setIndicator("本月消費");
thost.addTab(ts3);
thost.setCurrentTab(0);
}
}
注意第 10 行繼承 TabActivity , 第 15 行套用上述的 xml 佈局 ,接著就是對各個 TabWidget 的初始化(initView)
第 23 行取得 TabHost 物件 thost
第 25 ~ 30 行為建立第 1 個 TabWidget 的內容
第 26 行注意 Table_widget4.class 必須先建立好,這代表當點選該標籤頁就會執行的類別
第 27 行建立 TabSpec 物件, tab4 代表該標籤頁的 Tag,之後若有需要可取得 Tag 即可
第 28 行設定 Content 內容,其對應的類別為 Table_widget4.class
第 29 行顯示的內容
第 30 行加入TabSpec
接著選擇其中 1 個最簡單的 TabWidget 來看(Table_widget2.class),其內容為
package com.example.helloworld;
import android.app.Activity;
import android.os.Bundle;
public class Table_widget2 extends Activity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
}
是的~ 這個就是最簡單的 TabWidget ,當然你可以任意改寫其內容來達到需求
