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

Android 開發:自訂窗口標題欄的版面配置

編輯:關於 Android 開發

重點說明

一般應用的標題欄(Title)都是建立應用時在 AndroidManifest.xml 中配置的,或以 setTitle 設定一個簡單的字串。如果想在標題欄中加入按鈕、圖片等多個複雜的布局,就需要以下方法:在視窗建立時,把一個 XML 布局設定成該應用的 Title。

實作步驟

功能目標:把標題欄設定成「一個字串加上一個按鈕」的組合。

a) 修改 Activity 程式碼

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); // 注意順序,要在 setContentView 之前
    setContentView(R.layout.main);
    // 注意順序,setFeatureInt 最好在 setContentView 之後
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
}

b) 新增 title.xml 版面配置

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:text="text" />
    <Button android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="30px"
        android:text="button" />
</RelativeLayout>

注意事項

第一,務必留意順序:requestWindowFeature 要在 setContentView 之前呼叫,而 getWindow().setFeatureInt 最好放在 setContentView 之後。

第二,requestWindowFeature(Window.FEATURE_CUSTOM_TITLE) 不要與其他針對 Title 的 requestWindowFeature(xxxx) 設定一起使用,以免彼此衝突。

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