基本上我已经用尽了所有我发现的关于以编程方式更改状态栏颜色的帖子,但没有一个涉及这个特定案例。
我有一个包含 ViewPager 和 BottomNavigationView 的 Activity 。 ViewPager 包含三个 Fragment,BottomNavigationView 在它们之间移动并关闭 smoothscroll。
由于三个 Fragment 中的第一个是 map ,我希望状态栏在显示第一个 Fragment 时是透明的,但在其他两个 Fragment 上恢复为不透明颜色。
下面是一些代码,展示了我如何尝试设置和恢复状态栏状态。
private class TabSelectedObserver implements Observer<Integer> {
@Override
public void onChanged(@Nullable Integer selectedTab) {
if (selectedTab != null) {
activityMainBinding.mainPager.setCurrentItem(selectedTab, false);
switch (selectedTab) {
case 0:
applyTransparentStatusBarTheme();
break;
default:
applyOpaqueStatusBarTheme();
break;
}
}
}
}
private void applyTransparentStatusBarTheme() {
hideSystemUi();
getWindow().setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
}
private void applyOpaqueStatusBarTheme() {
showSystemUi();
getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.rippallete_700));
}
private void hideSystemUi() {
// Set flags for hiding status bar and navigation bar
mSystemUiVisibility = mSystemUiVisibility
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
getWindow().getDecorView().setSystemUiVisibility(mSystemUiVisibility);
}
private void showSystemUi() {
// Reset flags for hiding status bar and navigation bar
mSystemUiVisibility = mSystemUiVisibility
& ~View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
getWindow().getDecorView().setSystemUiVisibility(mSystemUiVisibility);
}
Here's a gif showing the behavior I end up with
我用 fitSystemWindows
尝试的每件事都没有产生我想要的结果。
如果有人对如何为每个 Fragment 提供单独的状态栏颜色有任何建议,其中 1 是透明的,我将不胜感激。
最佳答案
因此,假设您要根据您选择的任何选项卡的位置设置状态栏颜色,您可以执行与此类似的操作:
private void updateStatusBarColour(int tabPosition) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
switch (tabPosition) {
case FIRST_TAB:
case SECOND_TAB:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mRootView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
window.setStatusBarColor(ContextCompat.getColor(this, R.color.colorPrimaryLight));
break;
case THIRD_TAB:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mRootView.setSystemUiVisibility(0);
}
window.setStatusBarColor(ContextCompat.getColor(this, R.color.colorPrimary));
break;
case FOURTH_TAB:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mRootView.setSystemUiVisibility(0);
}
window.setStatusBarColor(ContextCompat.getColor(this, R.color.colorDarkTan));
break;
}
}
}
请注意,我在 mRootView
上调用了 setSystemUiVisibility
,其中 mRootView
是包含 ViewPager 的根父 View (或任何根布局你包含的 Activity )。该调用专门设置状态栏的主题,以便状态栏项目(如电池符号)可以在深色或浅色背景上可见,具体取决于您最终设置的颜色。
关于Android - 在 Viewpager 中的 fragment 之间切换状态栏透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44832273/