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

Android 自訂 ActionBar.Tab 的外觀表現

編輯:關於 Android 程式設計

最近想修改 ActionBar.Tab 的文字字型與顏色,卻發現該物件提供的介面非常有限,網上搜尋的結果也大多較舊,使用的並非 Google 官方範例中的 ActionBar。研究一整天後,找到了使用 setCustomView 來自訂 ActionBar.Tab 物件的方法。

做法是:先透過 ActionBar.getTabAt(int) 取得一個 ActionBar.Tab 物件,然後呼叫 setCustomView 使用自訂的 layout。注意這裡並非生成 layout 物件,而是直接使用該佈局,佈局中可預先設定文字大小、背景、顏色等。後續就和使用普通佈局一樣,取得 TextView 再設定文字、背景等。

actionBar = getSupportActionBar();
ActionBar.Tab t = actionBar.getTabAt(i);
t.setCustomView(R.layout.tab_layout_1);
TextView title = (TextView) t.getCustomView().findViewById(R.id.tab_title);
title.setBackgroundResource(R.drawable.detail);
title.setText(sectionID);

對應的自訂 tab 布局檔 tab_layout_1.xml:

<?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/tab_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_gravity="center_vertical|center"
        android:textColor="@android:color/holo_blue_dark"
        android:textSize="14sp" />
</frameLayout>

透過這種方式,即可自由定制 Tab 的文字樣式與外觀,突破原生物件介面有限的限制。

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