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

Android 全螢幕與移除標題欄的多種實作方式

編輯:關於 Android 程式設計

做遊戲、相機、影片播放或沉浸式展示頁時,往往需要把標題欄與狀態列都藏起來,讓內容佔滿整個螢幕。Android 上依需求範圍不同,有好幾種做法可以選。

1. 讓所有 Activity 都全螢幕

最省事的方式是在 AndroidManifest.xml 的 <application> 上直接指定主題:

android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

這樣整個 App 的每一個 Activity 都會是全螢幕無標題。

2. 讓單一 Activity 全螢幕

requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);

注意這兩行必須在 setContentView() 之前呼叫,否則會拋出例外。

3. 只移除標題欄

如果只想去掉標題,保留狀態列(電池、訊號那些),一行就夠:

requestWindowFeature(Window.FEATURE_NO_TITLE);

關於標題的幾個常用操作整理如下:

  • 改變標題內容:setTitle(CharSequence title)
  • 隱藏標題:requestWindowFeature(Window.FEATURE_NO_TITLE)
  • 隱藏標題並隱藏狀態列(即全螢幕):
public void setFullscreen() {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
}

4. 自訂標題內容

先關掉系統標題欄,再自己在版面裡放一個 TextView 顯示文字。

在 manifest 中為 Activity 加上 label:

<activity android:name=".activity.MainActivity"
    android:screenOrientation="portrait"
    android:label="@string/titlebar_text" />

在 Activity 中:

requestWindowFeature(Window.FEATURE_NO_TITLE); // 設置視窗無標題欄
setContentView(R.layout.main);
// 動態設置標題的值,getTitle() 的值是該 Activity 宣告中 android:label 的值
((TextView) findViewById(R.id.titlebar_text)).setText(getTitle());

這裡的巧妙之處在於:getTitle() 取得的正是 manifest 裡 android:label 設定的值,所以不必再另外維護一份標題字串。

5. 自訂標題版面配置

如果標題區不只是幾個字,還要放圖示、按鈕、進度條,那就該把標題當成一個獨立的 layout 來處理:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 預先設置允許改變的視窗狀態,需在 setContentView 之前調用,
    // 否則設置標題時拋運行時錯誤
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.custom_title);
    // 標題區域可設置為 layout,如此可以有豐富的展現方式
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_1);
}

對應的 res/layout/custom_title_1.xml 只需包含一個 TextView 來顯示標題即可。Android 允許把標題區做成一個完整的 layout,擴展性非常好:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/screen"
    android:layout_width="fill_parent"
    android:layout_height="fill_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" />

</RelativeLayout>

該選哪一種?

全 App 都沉浸式 → 用方式 1;單頁需要全螢幕 → 方式 2;只想去掉標題列 → 方式 3;標題文字需要動態變化 → 方式 4;標題區要放多個元件 → 方式 5。

補充:上述 SYSTEM_UI_FLAG 之前的老寫法在 Android 4.4 之後已被標示為不建議使用。目前的標準做法是改用 View.SYSTEM_UI_FLAG_IMMERSIVE 系列旗標,或直接套用 Theme.Material.NoActionBar.Fullscreen 之類的內建主題。另外 WindowManager.LayoutParams.FLAG_FULLSCREEN 這個用法雖然仍可用,但用於狀態列隱藏時,新專案更推薦 WindowInsetsController API。

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