以前做分頁我都用 GridView 加 ActivityGroup,一方面是覺得 TabHost 不好用,另一方面也得承認是自己功力不足。但其實只要願意重寫 view,多數問題都能解掉。以下示範如何消掉 TabHost 頁籤下方那條惱人的白線,過程相當簡單。
TabHost 的基本用法網上範例很多,這裡不重複,重點放在後處理。
程式碼
- public class MyActivity extends TabActivity {
- private TabWidget tabWidget;
- /** Called when the activity is first created. */
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Resources res = getResources(); // Resource object to get Drawables
- final TabHost tabHost = getTabHost(); // The activity TabHost
- TabHost.TabSpec spec; // Resusable TabSpec for each tab
- Intent intent; // Reusable Intent for each tab
- // Create an Intent to launch an Activity for the tab (to be reused)
- intent = new Intent().setClass(this, ArtistsActivity.class);
- // Initialize a TabSpec for each tab and add it to the TabHost
- spec = tabHost
- .newTabSpec("artists")
- .setIndicator("Artists",
- res.getDrawable(R.drawable.ic_tab_artists))
- .setContent(intent);
- tabHost.addTab(spec);
- // Do the same for the other tabs
- intent = new Intent().setClass(this, AlbumsActivity.class);
- spec = tabHost
- .newTabSpec("albums")
- .setIndicator("Albums",
- res.getDrawable(R.drawable.ic_tab_artists))
- .setContent(intent);
- tabHost.addTab(spec);
- intent = new Intent().setClass(this, SongsActivity.class);
- spec = tabHost
- .newTabSpec("songs")
- .setIndicator("Songs",
- res.getDrawable(R.drawable.ic_tab_artists))
- .setContent(intent);
- tabHost.addTab(spec);
- tabHost.setCurrentTab(2);
- View v;
- tabWidget = tabHost.getTabWidget();
- for (int i = 0; i < tabWidget.getChildCount(); i++) {
- // 獲取tabview項
- v = tabWidget.getChildAt(i);
- // 設置tab背景顏色
- v.setBackgroundResource(Android.R.color.white);
- // 獲取textview控件,(默認為白色)
- TextView textView = (TextView) v.findViewById(android.R.id.title);
- textView.setTextColor(Color.BLACK);
- // 默認選項要處理
- if (tabHost.getCurrentTab() == i)
- v.setBackgroundResource(R.drawable.renren_sdk_pay_repair_btn);
- }
- // tabchanged的監聽
- tabHost.setOnTabChangedListener(new OnTabChangeListener() {
- // tabId顯示的是:newTabSpec裡面的值
- @Override
- public void onTabChanged(String tabId) {
- // 首先把所有的view背景初始化了.
- for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
- View v = tabHost.getTabWidget().getChildAt(i);
- // 設置tab背景顏色
- v.setBackgroundResource(android.R.color.white);
- // 選中的進行處理
- if (tabHost.getCurrentTab() == i) {
- v.setBackgroundResource(R.drawable.renren_sdk_pay_repair_btn);
- }
- }
- }
- });
- }
- }
白線是怎麼被消掉的
關鍵只有三步。第一,取得 TabWidget 底下每個分頁 View,把背景改成白色,蓋掉系統預設那條分隔線;第二,TabHost 內的 TextView 預設字色是白色,在白色背景上會看不見,所以要抓出 android.R.id.title 改成黑色;第三,掛上 OnTabChangeListener,在切換時先把所有分頁背景重設為白,再把當前分頁設成高亮背景,避免選中態殘留。
要注意 setCurrentTab 必須在這段迴圈之前呼叫,否則「判斷當前分頁」的那個 if 永遠不會成立,初始高亮就會消失。
下圖為實機效果:
源碼下載
免費下載地址:https://linux.linuxidc.com/
帳號與密碼皆為 www.linuxidc.com
下載目錄:/2012年資料/8月/30日/Android TabHost解決下面白線