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

Android 自訂標題欄實作教學:告別系統預設 title bar

編輯:關於 Android 程式設計

系統預設的標題欄樣式往往無法滿足設計稿要求,這時候我們需要換成自訂版面。整個流程可以拆成六個環節。

一、先把 Activity 的父類改掉

移除 ActionBarActivity 的 import,讓 MainActivity 直接繼承 Activity:

public class MainActivity extends Activity  // 否則會拋出異常

注意這一步只影響主介面,其他頁面不受牽連。

二、在 MainActivity 中啟用自訂標題

this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
this.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);

requestWindowFeature 必須在 setContentView 之前呼叫,這是一個容易踩到的順序陷阱。第三行則是把 R.layout.title 這個自訂版面塞進標題欄的位置。

三、建立 title.xml

在 layout 目錄下新增標題欄專用版面:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/tbartxt"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:text="@string/app_name"
        android:textColor="#ffffff"
        android:textSize="19dp" />
</LinearLayout>

四、透過 style 調整外觀

在 values 目錄建立 style.xml,用來控制標題欄的背景色與高度(預設高度 26dip,可自行調整):

<resources>
    <style name="CustomWindowTitleBackground">
        <item name="android:background">#09adeb</item>
    </style>
    <style name="title_style" parent="android:Theme">
        <item name="android:windowTitleSize">26dip</item>
        <item name="android:windowTitleBackgroundStyle">@style/CustomWindowTitleBackground</item>
    </style>
</resources>

五、把主題套用到目標頁面

在 AndroidManifest.xml 中,為需要更換標題的 Activity 加上:

android:theme="@style/title_style"

六、別忘了收拾善後

以上做法屬於局部修改,只作用於你指定的 Activity。而且一旦標題欄被替換,整個頁面的可用區域會跟著改變,原本以「有標題欄」為前提寫好的版面檔往往需要同步微調,否則容易出現內容被遮擋或留白異常的情形。

實務建議:如果 App 內多數頁面都要自訂標題,與其逐頁覆寫主題,不如統一封裝一個自訂 TitleBar 的版面並用 include 引入,後續維護成本會低很多。

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