2
I’m trying to implement the functionality of going back and appearing to me the fragment
in which I was previously.
That is: fragment1, Fragment 2, Fragment 3 and Fragment 4.
I can go from Fragment 1 to 2, 3 and 4 and so on, since, I have a bottomNavigation
. What happens is that when I click the back button on the phone the app turns off and I can’t get back to the previous Fragment...
I’ve seen countless codes, but none of them could help me.
This is part of my MainActivity
of BottomNavigation
:
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
navigation.setSelectedItemId(R.id.navigation_user);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_user:
Navigation.findNavController(MainActivity.this, R.id.navHostFragment).navigate(R.id.user_dest);
activeFragment = new UserFragment();
return true;
case R.id.navigation_maps:
Navigation.findNavController(MainActivity.this, R.id.navHostFragment).navigate(R.id.maps_dest, bundle);
activeFragment = new MapsFragment();
return true;
case R.id.navigation_history:
Navigation.findNavController(MainActivity.this, R.id.navHostFragment).navigate(R.id.resume_dest);
activeFragment = new HistoryFragment();
return true;
}
return false;
}
};
A code I saw (most of the codes used the FragmentManager
):
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.replace(..............);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
I don’t know where to put these pieces of code or what parameters to put on fragmentTransaction.replace()
.
Some kind soul to help me?
I tried to do it here, but I did not succeed, in case I can please post the answer, it is something I have been trying for a long time, the most I can is to return the Fragment to the first Fragment and then in the promising back button, close the app, I will ask a similar question in the stack in English, if you have answer, put here. Abç
– Murillo Comino
If you are interested I have made this example: https://github.com/MurilloComino/BottomNavigationViewJetpack
– Murillo Comino