開發 Android 應用時,常會需要全螢幕、把標題欄換成自訂版面(例如放幾顆按鈕),或在標題左側掛一張圖示。這些都靠 requestWindowFeature(int featureId) 這支方法開啟窗體的擴充特性,參數是 Window 類別中定義的常數。以下把常用項目與實作步驟整理出來。
requestWindowFeature(Window.FEATURE_LEFT_ICON);
setContentView(R.layout.dialog_activity);
getWindow().setFeatureDrawableResource(
Window.FEATURE_LEFT_ICON, android.R.drawable.ic_dialog_alert);
順序很重要:requestWindowFeature 必須在 setContentView 之前呼叫,否則會拋出例外。
DEFAULT_FEATURES:系統預設狀態,一般不需指定。FEATURE_CONTEXT_MENU:啟用 ContextMenu,預設已開啟。FEATURE_CUSTOM_TITLE:自訂標題。只要標題欄要放按鈕等元件,就必須指定它。FEATURE_INDETERMINATE_PROGRESS:不確定型態的進度指示。FEATURE_LEFT_ICON:標題欄左側圖示。FEATURE_RIGHT_ICON:標題欄右側圖示。FEATURE_NO_TITLE:不要標題欄,全螢幕應用最常用。FEATURE_OPTIONS_PANEL:啟用「選項面板」,預設已開啟。FEATURE_PROGRESS:進度指示器功能。this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
只寫前兩行,標題欄會變成空白——因為還沒告訴系統要載入哪個版面。補上第三行的 setFeatureInt,把 R.layout.title 塞進標題欄,自訂標題就完成了。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon"/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="文本"/>
</LinearLayout>
這個版面裡擺了一張圖與一段文字。實務上你可以在這裡換成 Button、搜尋框或任何控制項,之後再用 findViewById 取得參照、掛上監聽器,標題欄就跟一般版面一樣好用。