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

Android TabHost與TabActivity:兩種標籤頁布局實作

編輯:關於 Android 程式設計

TabHost 有兩種常見用法:一種是「每頁一個 Activity」,另一種是「所有內容寫在同一個版面檔裡」。前者耦合低、結構清楚;後者寫起來快、適合簡單場景。本文兩種都實作一次,並說明 TabActivity 背後其實藏了什麼。

做法一:繼承 TabActivity,每頁一個 Activity

專案結構:

其中 black.gif 顧名思義就是黑底背景圖,grey.gif 則是灰色背景圖,兩張圖用來做標籤的選中/未選中狀態。

三個內容頁各自都是獨立的 Activity:

ArtistActivity.java

 package cn.com.tagview; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class ArtistActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView textView = new TextView(this); // 該文檔將會作為標簽的內容進行顯示 textView.setText("藝術內容"); setContentView(textView); } } 

MusicActivity.java

 package cn.com.tagview; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class MusicActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView textView = new TextView(this); // 該文檔將會作為標簽的內容進行顯示 textView.setText("音樂內容"); setContentView(textView); } } 

SportActivity.java

 package cn.com.tagview; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class SportActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView textView = new TextView(this); // 該文檔將會作為標簽的內容進行顯示 textView.setText("運動內容"); setContentView(textView); } } 

點擊對應標籤時,下方就顯示該 Activity 的內容。

ic_tab.xml——標籤狀態的切換規則:

 <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="https://schemas.android.com/apk/res/android" > <item android:drawable="@drawable/grey" android:state_selected="true" ></item> <item android:drawable="@drawable/black" ></item> </selector> 

這個檔案要放在 res/drawable 目錄下(本例放在 drawable-hdpi,實際上 drawable-hdpi、drawable-ldpi、drawable-mdpi 都屬於 drawable 系列)。它的作用是:當 state_selected="true"(標籤被選中)時顯示 grey,未選中時顯示 black。用 selector 而不是兩張圖硬切,是標準做法。

TagView.java:

 package cn.com.tagview; import android.app.TabActivity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.widget.TabHost; /** * @author chenzheng_Java * @description 注意,該類一定要繼承TabActivity */ public class TagView extends TabActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.main); // android代碼中訪問application資源的一個類 Resources resources = getResources(); // 獲取當前activity的標簽,該方法的實現中已經執行了setContentView(com.android.internal.R.layout.tab_content); TabHost tabHost = getTabHost(); // 每一個標簽項 TabHost.TabSpec spec; // 聲明一個意圖,該意圖告訴我們,下一個跳轉到的activity是ArtistActivity。 Intent intent = new Intent(this, ArtistActivity.class); /** * tabHost.newTabSpec("artist")創建一個標簽項,其中artist為它的標簽標識符,相當於jsp頁面標簽的name屬性 * setIndicator("藝術標簽",resources.getDrawable(R.drawable.ic_tab))設置標籤顯示文本以及標簽上的圖標(該圖標並不是一個圖片,而是一個xml文件哦) * setContent(intent)為當前標簽指定一個意圖 * tabHost.addTab(spec); 將標簽項添加到標簽中 */ spec = tabHost.newTabSpec("artist").setIndicator("藝術標簽", resources.getDrawable(R.drawable.ic_tab)).setContent(intent); tabHost.addTab(spec); Intent intent2 = new Intent(this, MusicActivity.class); spec = tabHost.newTabSpec("music").setIndicator("音樂標簽", resources.getDrawable(R.drawable.ic_tab)).setContent(intent2); tabHost.addTab(spec); Intent intent3 = new Intent(this, SportActivity.class); spec = tabHost.newTabSpec("sport").setIndicator("體育標簽", resources.getDrawable(R.drawable.ic_tab)).setContent(intent3); tabHost.addTab(spec); // tabHost.setCurrentTabByTag("music");設置第一次打開時默認顯示的標簽,該參數與tabHost.newTabSpec("music")的參數相同 tabHost.setCurrentTab(1);//設置第一次打開時默認顯示的標簽,參數代表其添加到標簽中的順序,位置是從0開始的哦。 } } 

注意這裡完全沒有呼叫 setContentView(),因為 getTabHost() 的實作中已經幫你執行了。指定預設頁有兩種方式:setCurrentTabByTag("music") 用標籤標識,setCurrentTab(1) 用索引(從 0 起算)。

AndroidManifest.xml:

 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="cn.com.tagview" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <!-- android:theme="@android:style/Theme.NoTitleBar" 的意思是將系統默認的tag標簽去掉,為咱們自己的標簽空出位置--> <activity android:name=".TagView" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- 在主配置文件中聲明用於標簽切換的3個activity,記住此處一定要聲明,否則會出錯 android:name="ArtistActivity"裡面ArtistActivity前面是否有.都可以,你只需要保證該類是在manifest標簽下package屬性的包中即可。 --> <activity android:name="ArtistActivity" android:label="@string/app_name"></activity> <activity android:name="MusicActivity" android:label="@string/app_name"></activity> <activity android:name="SportActivity" android:label="@string/app_name"></activity> </application> </manifest> 

三個內容 Activity 務必在清單檔註冊,漏掉任何一個,切到那一頁時就會直接閃退。另外 Theme.NoTitleBar 是為了把系統標題列藏起來,讓標籤頁佔據整個畫面。由於 getTabHost() 內部已設定版面,main.xml 在這個做法裡其實用不到。

關於 TabActivity 的設計思路

你會發現 TabHost–TabActivity 與 ListView–ListActivity 有個共同點:系統都提供了一個「已經幫你做完大部分事」的類別,你只要繼承它、補上自己的資料綁定即可。程式碼裡並不是沒有 setContentView(),只是被藏在父類實作中了——對使用者隱藏,不代表不存在。

這其實就是模板方法模式:系統提供一個骨架,其中某些步驟留成空的方法或可覆寫的環節,你繼承後填入自己的實作,讓整體符合需求。理解這個模式,之後看到各種 XxxActivity 就不會再覺得別扭。

這個做法的最大優點是低耦合:每頁都是獨立 Activity,彼此不認識,內容想放圖片、影片、地圖都可以,只要在該 Activity 中實作。範例為了簡單只放了文字。

做法二:繼承 TabActivity,用單一版面檔布局

專案結構:

main.xml:

 <?xml version="1.0" encoding="utf-8"?> <!-- 該布局文件定義了標簽的內容部分,該布局文件一定要以FrameLayout為根元素 --> <FrameLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <!-- 第一個標簽內容 --> <LinearLayout android:id="@+id/widget_layout_Blue" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <EditText android:id="@+id/widget34" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="EditText" android:textSize="18sp"> </EditText> <Button android:id="@+id/widget30" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button"> </Button> </LinearLayout> <!-- 第二個標簽內容 AnalogClock為鐘表組件--> <LinearLayout android:id="@+id/widget_layout_red" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <AnalogClock android:id="@+id/widget36" android:layout_width="wrap_content" android:layout_height="wrap_content"> </AnalogClock> </LinearLayout> <!-- 第三個標簽內容 RadioButton必須在RadioGroup中哦 --> <LinearLayout android:id="@+id/widget_layout_green" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <RadioGroup android:id="@+id/widget43" android:layout_width="166px" android:layout_height="98px" android:orientation="vertical"> <RadioButton android:id="@+id/widget44" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="RadioButton"> </RadioButton> <RadioButton android:id="@+id/widget45" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="RadioButton"> </RadioButton> </RadioGroup> </LinearLayout> </FrameLayout> 

TagHostTest.java:

 package cn.com.tagHost.test; import android.app.TabActivity; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.TabHost; public class TagHostTest extends TabActivity { private TabHost myTabhost; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); myTabhost = this.getTabHost(); /** * inflate(int resource, ViewGroup root, boolean attachToRoot) * resource 很顯然是一個資源索引id * 當attachToRoot為true時,root代表一個可放置於容器中的組件 * 當attachToRoot為false時,root僅代表一個存儲值的對象 * 該方法的意思是,將根據R.layout.main生成的標簽View,添加到由myTabhost.getTabContentView()獲得的父容器中 * LayoutInflater類的inflate方法中有如下片段 * if (root != null && attachToRoot) { root.addView(temp, params); } 其中temp是根據resource指定的資源生成的一個和標簽有關的view */ LayoutInflater.from(this).inflate(R.layout.main, myTabhost.getTabContentView(), true); myTabhost.setBackgroundColor(Color.argb(150, 22, 70, 150)); myTabhost.addTab(myTabhost.newTabSpec("One") .setIndicator("A").setContent(R.id.widget_layout_Blue)); myTabhost.addTab(myTabhost.newTabSpec("Two") .setIndicator("B", getResources().getDrawable(R.drawable.icon)) .setContent(R.id.widget_layout_green)); myTabhost.addTab(myTabhost.newTabSpec("Three") .setIndicator("C", getResources().getDrawable(R.drawable.icon)) .setContent(R.id.widget_layout_red)); } } 

這個做法只有兩步:

  1. 定義內容頁的版面檔,根節點必須是 FrameLayout,每頁用一個帶 id 的區塊包起來。
  2. 讓 Activity 繼承 TabActivity,用 LayoutInflater 把版面掛到 getTabContentView() 上,再用 setContent(id) 指定每個標籤對應哪一塊。

inflate(R.layout.main, myTabhost.getTabContentView(), true) 這行的第三個參數 true 代表 attachToRoot,也就是把 inflate 出來的 View 直接加進 root 容器。若傳 false,root 只用來提供 LayoutParams,不會真的掛上去。

兩種做法怎麼選

頁面內容彼此差異大、各自有獨立邏輯,選做法一(多 Activity),維持低耦合;頁面都很簡單、只是切換顯示不同區塊,選做法二(單一版面),省下三個 Activity 與清單檔宣告。

最後仍要提醒:TabActivity 與 TabHost 早已 deprecated,且同一個 Activity 內再開 Activity 的寫法在現行 Android 版本上有生命週期與返回鍵行為的問題。新專案請用 TabLayout + ViewPager2 + Fragment,概念對應很清楚——每個 TabSpec 就等於一個 Fragment,setContent 則換成 Fragment 的替換。本文的模板模式思路與 selector 用法則完全通用。

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