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

Android 5.0+ 狀態欄與 Toolbar 間出現黑線:elevation 與 DrawerLayout 解決方案

     編輯:程式設計疑難解答

現象

設置狀態欄透明並與 Toolbar 同色後,兩者交界處出現 1-2px 黑線/陰影線,影響沉浸式體驗。

根因

Material Design 預設給 Toolbar / AppBarLayout 設置了 elevation(陰影高度),在 API 21+ 上渲染為真實陰影,與透明狀態欄疊合產生視覺分割線。

解決方案對比

方案代碼優缺點
1. 移除 Toolbar elevationapp:elevation="0dp" 或 toolbar.setElevation(0)最簡單,但失去 Material 陰影層次感
2. 使用 DrawerLayout 作為根佈局根節點換 <DrawerLayout>,內含 <CoordinatorLayout>官方推薦,DrawerLayout 會正確處理狀態欄邊距,無黑線
3. 給 Toolbar 增加 fitsSystemWindowsandroid:fitsSystemWindows="true" + 主題 windowTranslucentStatus需配合主題微調,易產生其他邊距問題

推薦做法:DrawerLayout 根佈局

<androidx.drawerlayout.widget.DrawerLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:elevation="0dp" />  <!-- 可選:保留 0 陰影 -->

    </com.google.android.material.appbar.AppBarLayout>

    <!-- 內容區 -->
    <FrameLayout android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.drawerlayout.widget.DrawerLayout>

主題配置

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
</style>

總結

「黑線」本質是 **Toolbar elevation 陰影與透明狀態欄疊加**。最穩健方案:**根佈局用 DrawerLayout + fitsSystemWindows=true**,配合 windowTranslucentStatus 主題,徹底消除分割線並保持 Material 風格。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved