首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 界面被狀態欄遮擋問題的解決方案:fitsSystemWindows 屬性

     編輯:程式設計綜合問答

現象

  • 設置沉浸式狀態欄 (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) 後,內容區域頂部被狀態欄遮擋。
  • 部分頁面正常,部分頁面異常,提示「界面穿過狀態欄」。

根本原因

設置 fitsSystemWindows="true 後,View 會在佈局時預留系統窗口 (狀態欄/導航欄) 的內邊距,將內容下移。若根佈局未聲明此屬性,或中間佈局層級阻斷了 WindowInsets 分發,內容就會繪製到狀態欄下方。

解決方案

方案一:根佈局添加屬性 (最簡單)

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">
    <!-- 子 View 將自動獲得內邊距 -->
</LinearLayout>

方案二:程式化處理 (精細控制)

View rootView = findViewById(android.R.id.content).getRootView();
ViewCompat.setOnApplyWindowInsetsListener(rootView, (v, insets) -> {
    // 僅對特定子 View 應用內邊距
    View toolbar = findViewById(R.id.toolbar);
    ViewCompat.setPaddingRelative(toolbar,
        toolbar.getPaddingStart(),
        insets.getSystemWindowInsetTop(),  // 狀態欄高度
        toolbar.getPaddingEnd(),
        toolbar.getPaddingBottom());
    return insets.consumeSystemWindowInsets();
});

方案三:全屏佈局 + 手動 Padding (舊版兼容)

// 在 Activity onCreate 中
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    // 為根佈局設置上邊距 = 狀態欄高度
    View contentView = findViewById(android.R.id.content);
    contentView.setPadding(0, getStatusBarHeight(), 0, 0);
}

常見誤區

誤區正確認知
只在 Toolbar 加 fitsSystemWindows必須在**根佈局**或接收 WindowInsets 的父容器設置
ScrollView/RecyclerView 內部失效確保它們也是 fitsSystemWindows=true,或用 paddingTop 手動預留
設置后狀態欄顏色變灰需同時設置 window.setStatusBarColor(Color.TRANSPARENT) 配合透明狀態欄

驗證方法

  • 開啟「開發者選項 → 顯示佈局邊界」,觀察內容區域是否被狀態欄高度下移。
  • 使用 adb shell dumpsys window_display 查看 WindowInsets 分發鏈路。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved