編輯:Android 開發實例
TabHost 是 Android 中用來實作標籤頁(Tab)切換的容器控件,能讓使用者在多個頁面之間快速切換。以下從原理、關鍵方法到完整範例逐步說明。
TabHost 提供了一個專用的窗口視圖容器,內部包含兩個子元素:一組是讓使用者點選的標籤按鈕,另一組則是用來承載各分頁內容的 FrameLayout。需要注意的是,個別分頁的設定通常透過 TabHost 這個容器物件來控制,而不是直接設在子檢視上。
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/view1"
android:background="@drawable/b"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="頁1" />
<TextView android:id="@+id/view2"
android:background="@drawable/c"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="頁2" />
<TextView android:id="@+id/view3"
android:background="@drawable/d"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="頁3" />
</FrameLayout>
public class TabHostDemo extends TabActivity {
TabHost tabHost = getTabHost();
LayoutInflater.from(this)
.inflate(R.layout.tabhostpage, tabHost.getTabContentView(), true);
tabHost.addTab(tabHost.newTabSpec("tab1")
.setIndicator("分頁一")
.setContent(R.id.view1));
tabHost.addTab(tabHost.newTabSpec("tab2")
.setIndicator("分頁二")
.setContent(R.id.view2));
tabHost.addTab(tabHost.newTabSpec("tab3")
.setIndicator("分頁三")
.setContent(R.id.view3));
TabActivity 屬於較早期的實作方式,在新版 Android 開發中,官方已建議改用 Fragment 搭配 TabLayout 或 ViewPager 來實作分頁,因為它具備更好的生命週期管理與版面適應能力。若只是維護既有專案,理解 TabHost 的運作方式仍有其價值。
Android 本地化入門:靠資源資料夾自動切換語言
你的 App 可能同時被台灣、日本、德國的使用者開啟。如果介面永遠只有一種語言,對不諳該語言的人來說就是一道門檻。本地化要處理的範圍包括文字、數字格式、日期寫法,乃至於圖
Android大圖拖拽與多點縮放實現原理詳解
最近項目比較忙,博客擱置了有些日子,今天終於抽出時間,一口氣補上兩篇,過過癮。這篇要講的圖片拖拽縮放,也是我在實際項目中用到的功能,今天整理出來把源碼分享給大家,希望能給
Android 應用本地化:讓同一個 App 說各國語言
一個上架 Google Play 的 App,可能在幾十個國家的裝置上被開啟。使用者對「文字、數字、日期、檔案」的期待各不相同,如果 App 永遠只顯示一種語言,體驗與留
Android AppWidget 入門:桌面小工具的建立與跨行程互動
AppWidget 就是我們在桌面上看到的那種小方塊——天氣、行事曆、音樂播放控制,都屬於這一類。它讓使用者不必打開 App 就能完成操作或看到資訊。 本文分兩部分:先做