Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

改造 TabWidget:把直式圖文標籤改成自訂排列樣式

編輯:Android 開發實例

Android 常見的 TabHost 中,TabWidget 的標籤預設是「圖示在上、文字在下」的垂直排列,通訊錄就是這種風格。這種配置在手機直式螢幕上佔用最省,但換成橫式螢幕時,水準方向會顯得鬆散不夠緊湊。

想改成「圖片在左、文字在右」的橫向排列,關鍵是先理解 TabWidget 的內部結構。

理解 TabWidget 的三層結構

1. TabWidget 本質上是一個 horizontal 的 LinearLayout

2. 它包含的每個標籤又是一個 RelativeLayout

3. 每個標籤 RelativeLayout 裡面包含兩個 View:ImageView 與 TextView

有了這個理解,就能推導出它的版面骨架:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"

android:orientation="horizontal"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

<RelativeLayout

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="wrap_content">

<ImageView/>

<TextView/>

</RelativeLayout>

<RelativeLayout

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="wrap_content">

<ImageView/>

<TextView/>

</RelativeLayout>

...多個 RelativeLayout

</LinearLayout>

實作自訂配置

掌握結構後,做法就是「取出每個標籤的 RelativeLayout,把裡面的子 View 換成自己的配置」。以下以圖片在左、文字在右為例:

private void addToTabHost(String name, int image, int number){

//取得 TabHost 的第一個子容器,再取得其中的 TabWidget

LinearLayout ll = (LinearLayout) mTabHost.getChildAt(0);

TabWidget tw = (TabWidget) ll.getChildAt(0);

//取出第 number 個標籤的 RelativeLayout

RelativeLayout rl = (RelativeLayout) tw.getChildAt(number);

rl.addView(composeLayout(name, image), new LinearLayout.LayoutParams(

LinearLayout.LayoutParams.FILL_PARENT,

LinearLayout.LayoutParams.FILL_PARENT));

}

private View composeLayout(String name, int image){

LinearLayout layout = new LinearLayout(this);

layout.setGravity(Gravity.CENTER);

layout.setOrientation(LinearLayout.HORIZONTAL);

ImageView iv = new ImageView(this);

iv.setImageResource(image);

layout.addView(iv, new LinearLayout.LayoutParams(

LinearLayout.LayoutParams.WRAP_CONTENT,

LinearLayout.LayoutParams.FILL_PARENT));

TextView tv = new TextView(this);

tv.setGravity(Gravity.CENTER);

tv.setSingleLine(true);

tv.setPadding(10,0,0,0);

tv.setTextSize(18);

tv.setText(name);

layout.addView(tv, new LinearLayout.LayoutParams(

LinearLayout.LayoutParams.WRAP_CONTENT,

LinearLayout.LayoutParams.FILL_PARENT));

return layout;

}

這樣就實現了圖片在左、文字在右的配置。

composeLayout() 的設計值得學:它把「組出一塊標籤內容」獨立成一個方法,回傳一個 HORIZONTAL 的 LinearLayout,圖片與文字各佔一半空間,並用 tv.setPadding(10,0,0,0) 拉開間距、setSingleLine(true) 防止文字換行。addToTabHost() 則只負責定位與插入,職責切得很乾淨。

實作時要注意兩點。第一,addToTabHost() 必須在所有 tab 都已經用 newTabSpec().setContent() 加入 TabHost 之後呼叫,否則 getChildAt(number) 會拿到 null。第二,這種做法直接假定了 TabWidget 的內部視覺結構,屬於繞過公開 API 的取巧手段,一旦 Android 版本調整了內部實作就可能失效。若只是為了橫向排版,比較穩健的替代方案是改用 TabLayout(Design Support Library)或自訂 Fragment 搭配 ViewPager,並用自訂的 tab view 達成同樣的視覺效果。

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