Following is my code for bottom navigation view item selected
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.action_one:
// Switch to page one
fragment = FragmentA.newInstance();
break;
case R.id.action_two:
// Switch to page two
fragment = FragmentB.newInstance();
break;
case R.id.action_three:
// Switch to page three
fragment = FragmentC.newInstance();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.container,fragment,"TAG").commit();
return true;
}
});
Now my problem is every time fragment is re-created and don't want fragment to be recreated every time I also tried adding addToBackStack(null) but it this case on back button press keeps popping fragments from stack which I don't want.
Is there any way to display fragments on bottom navigation bar selected without re-creating fragment
Map<int, Fragment>
and each fragment have a static id. I create all Fragment inonCreate
of theActivity
. But it's not recommended. You can add the fragment in thebackstack
with a unique tag likeFragment.class.getSimpleName()
, then find it withfindFragmentByTag
and commit him again. Be sure to add eachFragment
one time to thebackstack
– HomeopathyonBackPressed()
in yourActivity
. Commentsuper.onBackPressed()
– Homeopathy