Search code examples
androidandroid-fragmentsandroid-activityandroid-fragmentactivitybottomnavigationview

Android Bottom View Activity multiple instances of fragments


I've created a app using Bottom View Activity. My problem is multiple instances of used fragments. I've written fragments's onPause and onResume to develop activity lifecycle, but when switching between fragments there are created two instances of each fragment, so these functions do not work properly.

I've seen this, but my main looks like that:

public class Main extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    BottomNavigationView navView = findViewById(R.id.nav_view);
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
    NavigationUI.setupWithNavController(navView, navController);
}
}

How to implement FragmentManager here?


Solution

  • You need to use:

    getSupportFragmentManager().beginTransaction().replace(
            R.id.your_fragment_container,
            YourFragment(),
            YourFragmentsTag
    )