Fragment not visible after when activity is recreated

266 Views Asked by At

I'm using a bottom navigation view with four fragments, to avoid recreation of fragments I'm using this code snippet:

private void changeFragment(Fragment fragment, String tagFragmentName) {
    FragmentTransaction ft = fm.beginTransaction();

    Fragment currentFragment = fm.getPrimaryNavigationFragment();

    if (currentFragment != null) {
        ft.hide(currentFragment);
    }

    Fragment fragmentTemp = fm.findFragmentByTag(tagFragmentName);

    if (fragmentTemp == null) {
        fragmentTemp = fragment;
        ft.add(R.id.content, fragmentTemp, tagFragmentName);
    } else {
        ft.show(fragmentTemp);
    }

    ft.setPrimaryNavigationFragment(fragmentTemp).commit();
}

private void showProspectFragment() {
    changeFragment(ProspectContainerFragment.newInstance(), ProspectContainerFragment.class.getSimpleName());
}

private void showChatsFragment() {
        changeFragment(ChatsFragment.newInstance(), ChatsFragment.class.getSimpleName());
}

....

// Bottom nav item click listener
binding.bottomNav.setOnNavigationItemSelectedListener(item -> {
        switch (item.getItemId()) {
            case R.id.prospect:
              showProspectFragment();
              return true;
            case R.id.chat:
                showChatsFragment();
                break;
            ...
        }
});

But whenever activity is recreated (using recreate()), for some reason fragments are not visible, no matter how many times I tap on bottom nav.

1

There are 1 best solutions below

1
On

Are you using show/hide functionality? If so, I think you must call one function in class onCreate method.