Android - Toggle status bar transparency between Fragments in a Viewpager

Viewed 968

I've exhausted essentially every post I've found regarding changing the status bar color programmatically, but none of them touch on this specific case.

I have an Activity that contains a ViewPager and a BottomNavigationView. The ViewPager holds three Fragments and the BottomNavigationView moves between them with smoothscroll turned off.

As the first of the three Fragments is a map, I'd like the status bar to be transparent when the first Fragment is shown, but revert back to its opaque color on the other two Fragments.

Here's some code that shows how I'm attempting to set and revert the status bar states.

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

Every thing I tried with fitSystemWindows didn't produce the result I wanted.

If anyone has any suggestions for how you would give each Fragment an individual status bar color, with 1 being transparent, I'd really appreciate it.

1 Answers
Related