Android Studio中Fragment显示灰色背景遮挡界面问题咨询
结论
这不是Fragment的正常显示效果,属于布局配置bug,你看到的灰色是Android系统默认窗口底色透出来了。
问题原因
HomeFragment根布局显式设置了透明背景android:background="@android:color/transparent",内部嵌套的ConstraintLayout是空布局、无任何背景,整体完全透明GalleryFragment根布局未配置background属性,默认也是透明状态- 宿主Activity的
content_main_app根布局、NavHostFragment容器均未设置背景,下层默认灰色窗口背景直接透到视图最上层,盖在所有控件下方 - 仅
HobbiesFragment配置了@drawable/beige1作为背景,因此该页面不会出现灰底问题,其余两个Fragment都会透出灰色
修复方法
二选一即可:
- 方案1:给每个Fragment根布局单独配置所需的背景色/背景图,不要留透明配置。
以HomeFragment为例,修改后布局代码如下:
<?xml version="1.0" encoding="utf-8"?> <layout> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".HomeFragment" android:background="@color/white"> <!-- 删除原有内部无意义的空ConstraintLayout,减少布局层级 --> </androidx.constraintlayout.widget.ConstraintLayout> </layout>
- 方案2:给NavHostFragment的父容器(即
content_main_app.xml的根ConstraintLayout)配置统一背景,所有Fragment默认继承该背景,无需逐个设置:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:showIn="@layout/app_bar_main_app"> <fragment android:id="@+id/nav_host_fragment_content_main_app" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="match_parent" app:defaultNavHost="true" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:navGraph="@navigation/mobile_navigation" /> </androidx.constraintlayout.widget.ConstraintLayout>
额外优化建议
- HomeFragment中嵌套的无任何子控件、无约束配置的空ConstraintLayout属于冗余代码,直接删除即可,多余的布局层级会拖慢渲染速度
- 仅当需要实现Fragment切换透明过渡、特殊浮层效果时,才将Fragment根布局设为透明,常规业务页面不要留透明根布局,避免透出下层无关内容
内容的提问来源于stack exchange,提问作者Josef M
相关产品推荐
相关产品推荐

