SlidingUpPanelLayout展开时需填满至状态栏顶部的透明化问题
解决SlidingUpPanelLayout展开时无法填满至透明状态栏顶部的问题
我之前也碰到过一模一样的问题!Navigation Drawer的适配逻辑确实没法直接套用到SlidingUpPanelLayout上,毕竟它的面板是动态滑动展开的,得针对性调整。给你几个亲测有效的方案:
方案一:监听面板状态,动态切换系统UI与状态栏属性
这是最稳妥的方案,核心思路是在面板展开时主动触发全屏+状态栏透明设置,收起时恢复原有状态:
- 先给布局里的
SlidingUpPanelLayout加上android:fitsSystemWindows="true" - 在代码中添加面板状态监听,动态调整窗口属性:
SlidingUpPanelLayout slidingUpPanel = findViewById(R.id.sliding_up_panel); slidingUpPanel.addPanelSlideListener(new SlidingUpPanelLayout.PanelSlideListener() { @Override public void onPanelSlide(View panel, float slideOffset) {} @Override public void onPanelStateChanged(View panel, SlidingUpPanelLayout.PanelState previousState, SlidingUpPanelLayout.PanelState newState) { if (newState == SlidingUpPanelLayout.PanelState.EXPANDED) { // 展开时设置全屏+状态栏透明 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { // Android 11+ 用WindowInsetsController替代旧标记 WindowInsetsController insetsController = getWindow().getInsetsController(); if (insetsController != null) { insetsController.hide(WindowInsets.Type.statusBars()); insetsController.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE); } getWindow().setStatusBarColor(Color.TRANSPARENT); } else { getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN ); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().setStatusBarColor(Color.TRANSPARENT); } } } else { // 收起时恢复原有UI状态 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { WindowInsetsController insetsController = getWindow().getInsetsController(); if (insetsController != null) { insetsController.show(WindowInsets.Type.statusBars()); } } else { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE); } // 恢复默认状态栏颜色 getWindow().setStatusBarColor(getResources().getColor(R.color.your_default_status_bar_color)); } } });
方案二:调整子布局的fitsSystemWindows属性
如果方案一还是有冲突,试试给SlidingUpPanelLayout的**子面板(即你要展开的内容布局)**设置android:fitsSystemWindows="false",让子布局直接延伸到状态栏下方。如果需要内容避开状态栏,可以动态给子布局顶部添加等于状态栏高度的padding:
// 获取状态栏高度 int statusBarHeight = 0; int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { statusBarHeight = getResources().getDimensionPixelSize(resourceId); } // 给子面板设置顶部padding View contentPanel = findViewById(R.id.sliding_content_panel); contentPanel.setPadding(0, statusBarHeight, 0, 0);
关键注意点
- 确保你的App主题中添加了
<item name="android:windowDrawsSystemBarBackgrounds">true</item>(Android 5.0+必填),否则setStatusBarColor不会生效 - 尽量移除
android:windowTranslucentStatus="true"属性,它会和全屏标记产生冲突,改用代码动态设置透明更可靠
内容的提问来源于stack exchange,提问作者the_dani
相关产品推荐
相关产品推荐

