I am facing an issue with my Android app where a double bottom navigation bar appears when the activity resumes from the background, such as when the user locks and unlocks their phone. This issue is not confined to a single device make or model but has been observed across various devices.
What I've tried so far:
Inspecting the activity's manifest configuration for any unintended relaunch behavior. Reviewing styles and themes for potential duplication of the navigation bar. Implementing log statements in activity lifecycle callbacks (onPause, onResume, etc.) to track activity state changes. Despite these efforts, the double navigation bar still appears intermittently upon resuming the activity.
My bottom nav code so far:-
bottomNavigationView.setOnItemSelectedListener(item -> {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
// Hide all existing fragments to prevent them from overlapping
Fragment currentFragment = fragmentManager.getPrimaryNavigationFragment();
if (currentFragment != null) {
transaction.hide(currentFragment);
}
String tag;
Fragment fragment;
switch (item.getItemId()) {
case R.id.nav_stories_new:
tag = "stories";
fragment = fragmentManager.findFragmentByTag(tag);
if (fragment == null) {
fragment = new StoriesFragment();
transaction.add(R.id.fragment_container_new, fragment, tag);
} else {
transaction.show(fragment);
}
break;
case R.id.nav_play_new:
tag = "play";
fragment = fragmentManager.findFragmentByTag(tag);
if (fragment == null) {
fragment = new PlayFragment();
transaction.add(R.id.fragment_container_new, fragment, tag);
} else {
transaction.show(fragment);
}
break;
default:
return false;
}
transaction.setPrimaryNavigationFragment(fragment); // Set the fragment to be the primary navigation fragment
transaction.commit();
return true;
});
// Restore the selected fragment on configuration changes
if (savedInstanceState == null) {
bottomNavigationView.setSelectedItemId(R.id.nav_stories_new);
} else {
// Restore the active fragment based on the saved instance state
String activeTag = savedInstanceState.getString("active_fragment_tag");
Fragment activeFragment = getSupportFragmentManager().findFragmentByTag(activeTag);
if (activeFragment != null) {
getSupportFragmentManager().beginTransaction().show(activeFragment).commit();
}
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
// Save the currently selected fragment tag
Fragment currentFragment = getSupportFragmentManager().getPrimaryNavigationFragment();
if (currentFragment != null) {
outState.putString("active_fragment_tag", currentFragment.getTag());
}
}