Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 開發入門:Tab 選項卡元件實作教學

Tab 選項卡是組織多頁內容時非常順手的元件:使用者點一下標籤就能切換畫面,不必層層跳轉。以下整理它的使用步驟與兩種內容承載方式。

一、使用 Tab 的四个步骤

  1. 在版面配置檔中以 FrameLayout 同時列出 Tab 元件本身,以及各個 Tab 要顯示的內容元件。
  2. 讓 Activity 繼承 TabActivity。
  3. 呼叫 getTabHost() 取得 TabHost 物件。
  4. 透過 TabHost 逐一建立 Tab 選項。

二、兩種承載 Tab 內容的做法

第一種是「同一個 Activity 內切換」:所有 Tab 的內容都放在同一份版面配置裡,切換時只是改變顯示的 id,實作最簡單,適合內容份量不大的情況。

MainActivity.java

package com.Android.tab.activity;

import android.app.TabActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.TabHost;

public class MainActivity extends TabActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 獲得 TabHost 物件
        TabHost tah = getTabHost();

        // from(this) 從 TabActivity 獲取 LayoutInflater
        // R.layout.main 存放 Tab 布局
        // 通過 TabHost 獲得存放 Tab 標簽頁內容的 FrameLayout
        // 是否將 inflate 加到根布局元素上
        LayoutInflater.from(this).inflate(R.layout.main, tah.getTabContentView(), true);

        // 設置 Tab 標簽的內容和顯示內容
        tah.addTab(tah.newTabSpec("tab1").setIndicator("圖片1").setContent(R.id.TextView01));
        tah.addTab(tah.newTabSpec("tab2").setIndicator("圖片2").setContent(R.id.TextView02));
        tah.addTab(tah.newTabSpec("tab3").setIndicator("圖片3").setContent(R.id.TextView03));
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/FrameLayout01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
    <TabHost
        android:id="@+id/TabHost01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <TextView
        android:id="@+id/TextView01"
        android:background="@drawable/pic1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <TextView
        android:id="@+id/TextView02"
        android:background="@drawable/pic2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <TextView
        android:id="@+id/TextView03"
        android:background="@drawable/pic3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</FrameLayout>

效果圖:

650) this.width=650;" height=120>

第二種做法是「每個 Tab 各自對應一個 Activity」,透過 setContent(Intent) 指定,適合每頁內容都相當複雜、需要獨立生命週期管理的場景。判斷標準很單純:內容輕就用 id 切換,內容重就拆成獨立 Activity。

Copyright © Linux教程網 All Rights Reserved