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

Android 面板控件 Tab 的使用方法

編輯:Android 開發實例

在手機有限的螢幕空間裡,當我們需要安排較多內容而無法全部容納時,除了使用版面捲動功能(但這樣做往往不夠美觀),更好的方式是使用面板 Tab 控件。特別是當我們需要把不同功能集合的控件各自歸類到獨立面板時,Tab 控件就顯得格外好用。

面板控件的好處在於:能在同一個界面上呈現不同的面板內容,並透過面板標籤方便地切換。以下直接從範例介紹 Tab 控件的兩種顯示方法。

一、在版面檔中定義各 Tab 的內容

以下以 TextView 為例,定義兩個 Tab 各自要顯示的內容:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent">
    <!-- Tab 1 中顯示的內容 -->
    <TextView android:id="@+id/content1" android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="tab1 content" />
    <!-- Tab 2 中顯示的內容 -->
    <TextView android:id="@+id/content2" android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="tab2 content" />
</FrameLayout>

二、在程式中使用 Tab 並載入版面控件

public class _Tab extends TabActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TabHost tabHost = getTabHost();
        LayoutInflater.from(this).inflate(R.layout.tab, tabHost.getTabContentView(), true);
        // Tab 1 的內容
        tabHost.addTab(tabHost.newTabSpec("tab1")
            .setIndicator("tab1", getResources().getDrawable(R.drawable.p1))
            .setContent(R.id.view1));
        // Tab 2 的內容
        tabHost.addTab(tabHost.newTabSpec("tab2")
            .setIndicator("tab2", getResources().getDrawable(R.drawable.p1))
            .setContent(R.id.view2));
        // Tab 3 的內容(用指定的 Activity 來設定 Tab 的內容)
        tabHost.addTab(tabHost.newTabSpec("tab3")
            .setIndicator("tab3", getResources().getDrawable(R.drawable.p1))
            .setContent(new Intent(this, _TextView.class)));
    }
}

重點方法說明

由以上範例可見,Tab 的使用主要環繞三個方法:

  • addTab:新增一個 Tab 頁面。
  • setIndicator:設定 Tab 的標籤文字與圖示。
  • setContent:設定 Tab 的內容來源。

值得一提的是,除了使用版面檔來定義 Tab 中顯示的內容,我們還可以直接把另一個 Activity 作為 Tab 的內容來顯示(如上例的 tab3),如此一來每個 Tab 面板的內容便能各自獨立,讓複雜的介面也能保持清晰的結構。

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