Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android 頁籤(TabHost)的實作步驟

編輯:進階開發

Android 的程式撰寫方式相當直覺,方便開發者快速實作各種功能。以下從頁籤的實作來看整個流程。

版面配置

先建立 Android 專案,把 Activity 命名為 HelloTabWidget。接著在 main.xml(或自訂的 XML 檔)中建立一個 TabHost,它需要兩個元素:TabWidget 與 FrameLayout,通常會把這兩者放進 LinearLayout 裡。FrameLayout 作為切換內容用的容器。

要特別注意:TabWidget 與 FrameLayout 使用不同的 ID 命名空間,寫成 android:id="@android:id/xxx" 這個形式是必要的,TabHost 才能自動找到它們。另外,Activity 必須繼承 TabActivity。

<?XML version="1.0" encoding="utf-8"?>
<TabHost XMLns:android="https://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <TextView
                android:id="@+id/textview1"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="this is a tab" />

            <TextView
                android:id="@+id/textview2"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="this is another tab" />

            <TextView
                android:id="@+id/textview3"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="this is a third tab" />

        </FrameLayout>
    </LinearLayout>
</TabHost>

Activity 程式碼

類別宣告要繼承 TabActivity:

public class HelloTabWidget extends TabActivity {

接著在 onCreate 中把頁籤掛上去:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mTabHost = getTabHost();
    mTabHost.addTab(mTabHost.newTabSpec("tab_test1")
            .setIndicator("TAB 1").setContent(R.id.textview1));
    mTabHost.addTab(mTabHost.newTabSpec("tab_test2")
            .setIndicator("TAB 2").setContent(R.id.textview2));
    mTabHost.addTab(mTabHost.newTabSpec("tab_test3")
            .setIndicator("TAB 3").setContent(R.id.textview3));

    mTabHost.setCurrentTab(0);
}

幾個實作提醒

newTabSpec 的參數是這個頁籤的 tag,setIndicator 決定標籤上顯示的文字(也可以傳入 View 做自訂樣式),setContent 則指定切到該頁時要顯示的內容——這裡直接指向 FrameLayout 中的某個子 View ID。實務上更常見的做法是把 setContent 指向一個 Intent,讓每個頁籤各自對應一個獨立的 Activity。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved