[Android] TabHost建立Custom Tab


建立Tab View的三種方式系列文章中,介紹了Android Tab Layout的組成要件(Tab Host, Tabs, TabContentView)以及三種建立基本Tab View的方法,這一次把討論的焦點放在tab上,tab負責切換TabContentView的元件,與User互動密切。預設的tab顯示型式有兩種:文字、文字+圖,只要在建立tabSpec時呼叫setIndicator(CharSequence label)、setIndicator(CharSquence label, Drawable icon),就可以產生基本的tab。


預設tab的限制

採用預設的tab設定方式十分方便,但同時也有很多限制,包含了圖文的排版是固定的(圖上文下)、高度固定、tab selected/unselected狀態顯示呈現效果固定…等,對於需要客製化tab的人而言,就不是這麼的好用,因此Android提供了另一個函式setIndicator(View view),讓開發者可以針對需求進行tab客製化,本文將針對如何在TabHost中加入自訂的Custom Tab。

程式碼說明:

(註:建立TabHost的部份,由於先前文章已提過,因此將不再贅述)

1、建立tab layout描述xml檔案
建立負責顯示Custom Tab的Layout xml,它包含了一個ImageView(icon)和一個TextView(label),[注意]由於tab的選取效果要客製化,所以下列屬性-ImageView的src、TextView的textColor以及LinearLayout的background將會在步驟2定義。

custom_tab.xml

2、tab狀態效果selector
完成tab的客製化Layout之後,再來就是tab狀態變化效果,本文將針對下列三種效果進行變更。

(1) Icon圖示:以selector描述tab icon在選取/非選取狀態時的圖片來源

tab_icon.xml

(2) 文字顏色:將文字在選取/非選取狀態時的顏色定義在selector中

text_focusable_color.xml

(3) 背景圖片:針對選取/非選取狀態設定不同的背景圖片(selected:粉, deselected:灰)

background_selector.xml

3、以setIndicator(View view)將客製化tab加入tab host
定義createCustomTab(String label, int iconID)函式,它負責回傳一個自定義的tab view,再利用setIndicator(view)將custom view指定為tab。

/***產生Custom tab view object
*@param label
*  tab顯示名稱
*@param iconID
*  tab icon的drawable id 
**/
private View createCustomTab(String label, int iconID){
 //產生Custom tab view object
 View tab = LayoutInflater.from(this)
     .inflate(R.layout.custom_tab, null);
    	
 //tab label
 TextView text = 
   (TextView)tab.findViewById(R.id.text);
 text.setText(label);
    	
 //tab icon
 ImageView img = 
   (ImageView)tab.findViewById(R.id.icon);
 img.setBackgroundResource(iconID);

 return tab;    	
}

//設定各tab頁面by指定View id
//in onCreate(Bundle instance)
tabHost.addTab(tabHost
  .newTabSpec("tab1")
  .setIndicator(
   createCustomTab("tab1", R.drawable.tab_icon)
  )
  .setContent(new Intent(this, Tab1.class))
 );
         
tabHost.addTab(tabHost
  .newTabSpec("tab2")
  .setIndicator(
   createCustomTab("tab2", R.drawable.tab_icon)
  )
  .setContent(new Intent(this, Tab2.class))
 );

最後程式執行結果如下:


留言

這個網誌中的熱門文章

[Android] layout_weight的妙用-讓View的大小以百分比率顯示(proportionate size)

[Android] 內部儲存體(Internal Storage)的檔案系統讀寫(File I/O)

【海外婚紗】道具行李篇