Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發筆記:用 TabHost 創建標籤式版面

編輯:關於 Android 程式設計

利用 TabHost 創建標籤式的版面配置,切換不同標籤時顯示對應內容與背景。效果如下所示:

1、添加 6 張圖片資源(直接拖入 drawable 文件夾),分別為 gray.png、white.png、gray2.png、white2.png、gray3.png、white3.png,代表標籤默認狀態與按下後的狀態。

2、在 drawable 文件夾中新建 XML 檔 picture.xml、picture2.xml、picture3.xml,分別填入以下內容。

picture.xml

<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/white" android:state_selected="true" />
    <item android:drawable="@drawable/gray" />
</selector>

picture2.xml

(同上結構,換成 white2 / gray2)

picture3.xml

<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/white3" android:state_selected="true" />
    <item android:drawable="@drawable/gray3" />
</selector>

3、在 activity_main.xml 中添加控件,並在 MainActivity.java 中調用。

activity_main.xml

<FrameLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.test2.MainActivity"
    tools:ignore="MergeRootFrame">
    <TextView
        android:id="@+id/view1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/view2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/view3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</FrameLayout>

MainActivity.java:

package com.example.test3;

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

public class MainActivity extends TabActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TabHost tabHost = getTabHost();
        LayoutInflater.from(this).inflate(
                R.layout.activity_main, // 加載頁面
                tabHost.getTabContentView(), true);
        tabHost.addTab(tabHost.newTabSpec("tab1")
                .setIndicator("tab1", getResources().getDrawable(R.drawable.picture))
                .setContent(R.id.view1));
        tabHost.addTab(tabHost.newTabSpec("tab2")
                .setIndicator("tab2", getResources().getDrawable(R.drawable.picture2))
                .setContent(R.id.view2));
        tabHost.addTab(tabHost.newTabSpec("tab3")
                .setIndicator("tab3", getResources().getDrawable(R.drawable.picture3))
                .setContent(R.id.view3));
        tabHost.setCurrentTab(1);
    }
}

4、測試後若出現「只顯示文字、不顯示圖標」的情況,可在 AndroidManifest.xml 中進行相應調整,最終即可正常顯示圖標。

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