本文接續 Action Bar 的應用,說明如何在 Action Bar 中加入自定義 View。這次範例會放入標題與 Spinner,讓工具欄能顯示更多互動內容。
先建立 action_bar.xml,可使用 LinearLayout 包含 TextView 與 Spinner。這個布局就是未來要放進 Action Bar 的內容。
Spinner 的項目可重用既有列表項布局,例如包含 ImageView 與 TextView 的 drawer_item.xml。
在 onCreate 中,以 LayoutInflater 載入自定義布局,取得 Spinner 並設定 Adapter。接著啟用 setDisplayShowCustomEnabled,再呼叫 setCustomView,讓自定義 View 顯示在 Action Bar。
為 Spinner 設定 OnItemSelectedListener,在 onItemSelected 中取得被選取的項目,再依需求更新畫面或填入資料。