編輯:Android 程式設計入門
傳統的手機狀態列是一條黑色或白色的條狀區域,有些還會與 App 主介面有明顯色差。這條區域在視覺上切走了一部分高度,讓可用畫面變小,也讓整體設計顯得割裂。
沉浸式做法則讓狀態列變成透明,內容得以延伸到它下方,視覺面積變大、質感也更統一。看看 QQ 這類應用的處理就很直觀:

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setImmerseLayout(findViewById(R.id.leave_message_layout));
// 讓狀態列透明
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// 讓導航列透明
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
}
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:paddingLeft="5dp"
android:fitsSystemWindows="true"
android:clipToPadding="true"
android:textColor="#f1e5e5"
android:text="你有男朋友嗎?"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#009959" />
</LinearLayout>
真正讓版面不被狀態列遮住的,是這兩行:
android:fitsSystemWindows="true" android:clipToPadding="true"
它們的作用需要分清楚:fitsSystemWindows="true" 會讓該 View 依系統窗體的 insets 自動加上對應的 padding,內容因此不會被狀態列壓住;而 clipToPadding="true" 決定 padding 區域要不要一併裁掉。兩者搭配,才能達到「背景色延伸到狀態列下方,但文字內容正常避開」的效果。

把 fitsSystemWindows 加在你要「被壓」的那層 View 上即可。加在根配置有時會導致整頁都被推開,反而失去沉浸式效果,這是最常出現的疑問。
如果頂部是淺色背景,深色圖示才看得清楚。FLAG_TRANSLUCENT_STATUS 無法控制圖示顏色,需要改用 Android 6.0 以上的 View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR:
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
沉浸式狀態列與 adjustResize 模式下的軟鍵盤經常互相干擾,會出現輸入框被鍵盤擋住、或整個版面被頂上去的狀況。常見解法有兩種:一是對特定頁面關閉沉浸式處理;二是自行監聽版面高度變化(例如使用 WindowInsetsAnimation 或自訂的軟鍵盤監聽工具類)手動計算並平移輸入區。這部分牽涉到不同 Android 版本的 insets 行為差異,需要逐版本實測。
FLAG_TRANSLUCENT_STATUS 屬於較早期的寫法。若 targetSdkVersion 已達 30 以上,建議改用 WindowCompat.setDecorFitsSystemWindows(window, false) 搭配 WindowInsetsControllerCompat 來控制,這是 AndroidX 提供的相容做法,在版本適應上更省心。
Android Studio 入門指南:從專案建立到模擬器測試
Android Studio 是以 IntelliJ IDEA 為基礎的 Android 整合開發環境,提供專案建立、版面預覽、模擬器、靜態分析與簽章打包等功能。以下整理
【入門篇】Android 學習筆記——項目結構及相關基礎知識
Android 項目有其自身的結構規範,良好地遵循結構規範可以讓開發事半功倍。下圖分別從 Android 視圖和 Project 視圖展示了項目結構: 圖中左側是 An
ListView 實現加載不同 Item 布局的詳解
在 Android 應用開發中,ListView 幾乎是必備組件,通常用於展示列表類型的數據。普通的數據展示並不難,借助 Volley、Xutils 等框架請求數據,再配
Android 補間動畫 TweenAnimation 用法整理
補間動畫(Tween Animation)是 Android 最直覺的動畫方案:你只要描述「從哪個狀態變到哪個狀態、花多久時間」,系統就會自動補上中間的過渡影格。以下把程