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

Android ActionBar 用法詳解:從主題、選單到自訂 View

編輯:關於 Android 程式設計

ActionBar 介紹

ActionBar 位於 Activity 頂部,通常用來顯示應用程式圖示、標題與操作選單。它也可用於導航與 View 交互。

ActionBar 大致可分為三部分:左側圖示、右側操作項目,以及 overflow 按鈕。

ActionBar 結構

加入 ActionBar

ActionBar 從 Android 3.0 開始提供。若要在低版本使用,可透過 Support Library v7。常見做法是讓 Activity 繼承 AppCompatActivity,並使用 AppCompat 主題。

在 styles.xml 中,可將主題 parent 設定為 Theme.AppCompat.Light.DarkActionBar,並設定 colorPrimary、colorPrimaryDark、colorAccent 等顏色。

ActionBar 主題

ActionBar 效果

移除 ActionBar

若要移除 ActionBar,可改用 NoActionBar 主題,或在程式碼中取得 ActionBar 後呼叫 hide。

修改樣式

ActionBar 的標題通常來自 Activity 的 label。若要顯示圖示,可在 v7 包中啟用 home 與 logo 顯示。

ActionBar 圖示與標題

加入選單項目

可在 menu 資源中定義 action item,並使用 showAsAction 控制顯示方式。never 表示不顯示在 ActionBar,ifRoom 表示有空間才顯示,always 表示永遠顯示在 ActionBar。

接著在 Activity 中重寫 onCreateOptionsMenu 與 onOptionsItemSelected,即可處理選單點擊。

ActionBar 選單

使用自訂 View

若需要更高度自訂,可建立自訂 layout,透過 LayoutInflater 載入,再設定為 ActionBar 的 custom view。

自訂 ActionBar

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