I tried doing this in Kotlin, hope it will be a help.
first, create different fragments and any navigation you want to after that create a function which will be used to load fragments into the activity.
when (item.getItemId()) {
R.id.home -> {
//this is the name of the method I am using for adding fragments
//with bottom navigation bar you can use it with any type o navigation.
loadFragment(getString(R.string.home_fragment), HomeFragment());
appBar.title = "Home"
return true
}
R.id.jobs -> {
loadFragment(getString(R.string.jobs_fragment), JobsFragment());
appBar.title = "Jobs"
return true
}
after that here is the method
private fun loadFragment(tag: String,loadFragment: Fragment) {
val fManager = supportFragmentManager
val fTransaction = fManager.beginTransaction()
val fragment = fManager.findFragmentByTag(tag)
if (fragment == null) {
fTransaction.replace(R.id.activity_main_content_main, loadFragment,tag);
} else { // re-use the old fragment
fTransaction.replace(R.id.activity_main_content_main, fragment, tag);
}
fTransaction.addToBackStack(tag);
fTransaction.commit();
}
first val fragment = fManager.findFragmentByTag(tag) this will search if the fragment is already loaded then else statement will be executed and the preloaded fragment will be displayed but if not
then loadFragment parameter we passed contains the fragment you want to load then if statement will be executed which will load the passed fragment.