0

While switching between fragments using bottomNavigationView the fragments are recreated every time when button is pressed.

Here is my code:

private boolean loadFragment(Fragment fragment) {
    //switching fragment
    if (fragment != null) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragmentguest, fragment)
                .commit();
        return true;
    }
    return false;
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
     Fragment fragment = null;

    switch (item.getItemId()) {
        case R.id.eventsguest:
            fragment = new Events();
            break;
        case R.id.about_usguest:
            fragment = new About_Us();
            break;
    }

    return loadFragment(fragment);
}

2 Answers2

0

Do not create fragment every time (fragment = new Events();) You can keep the reference of both the fragments in object fields and return the already created fragment in your onNavigationItemSelected method.
Or you can combine ViewPager with the BottomNavigationView. Refer this article and if you do not know much about ViewPager. Refer this.

Binary Baba
  • 1,953
  • 2
  • 16
  • 23
0

The replace method destroys your fragments. One workaround is to set them to Visibility.GONE, another (less easy) method is to hold them in a variable. If you do that, make sure you don't leak memory left and right.

this question answered by meredrica in here

Mehdi Varse
  • 271
  • 1
  • 15