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

Android ApiDemos 解析(5):App → Activity → Custom Title

編輯:Android 開發教學

Android UI 預設的標題欄由 android:label 決定內容,固定顯示在螢幕左上角。這個位置幾乎被浪費掉了——為什麼不能放點更有用的東西?Android 允許你自訂標題欄,用自己的 Layout 完全取代它,做出諸如 Windows Mobile 風格那樣的抬頭資訊列。

自訂標題欄的版面

App → Activity → Custom Title 把標題欄重新定義成左右兩個文字方塊,Layout 定義在 R.layout.custom_title_1:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/screen"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView android:id="@+id/left_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:text="@string/custom_title_left" />

    <TextView android:id="@+id/right_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="@string/custom_title_right" />

</RelativeLayout>

就是一個靠左、一個靠右的文字方塊,中間的空白剛好可以放標題文字或狀態圖示。

Window 與 Feature 機制

除了 setContentView 設定的 Content View,每個 Activity 還有一個 Window 物件。Window 負責管理視窗層級的外觀,包括標題欄——它可以讓你自訂標題欄,也可以讓你完全不顯示標題欄。

Window 定義了一系列 Feature 供開發者調整,自訂標題欄對應的 Feature ID 就是 Window.FEATURE_CUSTOM_TITLE:

requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.custom_title);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_1);

順序是關鍵

這段程式碼有個很容易出錯的地方:requestWindowFeature 必須在 setContentView 之前呼叫。一旦內容檢視已經設定,視窗的裝飾就已經定型,此時再請求更換 Feature 會直接拋出例外。

同一個規則也適用於全螢幕設定——requestWindowFeature(Window.FEATURE_NO_TITLE) 與 setFlags(FLAG_FULLSCREEN) 都必須寫在 setContentView 之前。把這三行就是想清楚順序再寫,能省下不少除錯時間。

最後,如果你只是想「隱藏」標題欄而非「自訂」,那麼 requestWindowFeature(Window.FEATURE_NO_TITLE) 一行就夠了;只有当你要放自己的內容上去時,才需要走 FEATURE_CUSTOM_TITLE 這條路。

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