Thursday, 1 August 2019

Android BottomNavigation fragment show/hide after App force terminate

I am trying to simulate App exit in background (LowMemory e.t.c), but after the App the is restored, the BottomNavigation fragments won't work anymore.

I have the following Array / vars

private Fragment[] fragments = new Fragment[]{new HomeFragment(), new MapFragment(), new SavedFragment(), new NotificationsFragment()};
private int selected = -1;

In onCreateView I am calling...

// open first Fragment when app starts
if (savedInstanceState == null) switchFragment(0, ShoutsHomeFragment.TAG); 
else selected = savedInstanceState.getInt(SELECTED_FRAGMENT);

switchFragment looks like

private void switchFragment(int index, String tag) {
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    Fragment fragment = fragmentManager.findFragmentByTag(tag);
    // creating for the first time
    if (fragment == null) transaction.add(R.id.tab_fragment_container, fragments[index], tag);
    if (selected >= 0) transaction.hide(fragments[selected]);   // <--- don't work
    if (fragment != null) transaction.show(fragment);           // <--- don't work
    transaction.commit();
    selected = index;
}

So, transaction.hide and transaction.show is not working after restoring the App, it stays on the same Fragment when I tap on other items on the BottomNavigation

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
        case R.id.navigation_shouts_home:
            switchFragment(0, HomeFragment.TAG);
            return true;
        case R.id.navigation_heat_map:
            switchFragment(1, MapFragment.TAG);
            return true;
        case R.id.navigation_loved:
            switchFragment(2, SavedFragment.TAG);
            return true;
        case R.id.navigation_notifications:
            switchFragment(3, NotificationsFragment.TAG);
            return true;
}

I programmed it this way so that I can retain Fragments (scroll) position when switching between items on BottomNavigation. So I want to show/hide instead of creating new Instance every time. Any help is appreciated.



from Android BottomNavigation fragment show/hide after App force terminate

No comments:

Post a Comment