Reputation: 85
I have an activity with 4 fragments. on fragment 3 there is a button when i click on that button i go to some other activity(Like TestActivity). I use this code to go from fragment 3 to that TestActivity:
startActivity(new Intent(getActivity(), TestActivity.class));
When i press back button on TestActivity it redirect me to the 1st Fragment(Default) of Main Activity. I want that when user press back on TestActivity to again come to Fragment 3. Please suggest me how i achieve this behaviour. Thanks
Upvotes: 1
Views: 278
Reputation: 1660
First of all you should know it has difference between fragment
and activity
back stack.
In change your fragment
you should use add addToBackStack("name")
, something like this :
KOTLIN :
In fragment
:
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.framelayout_main_fragmentContainer,SecondFragment())
.addToBackStack("first")
.commit()
In activity
:
supportFragmentManager.beginTransaction()
.replace(R.id.framelayout_main_fragmentContainer,Firstfragment())
.addToBackStack("first")
.commit()
JAVA :
getFragmentManager().beginTransaction().
replace(R.id.framelayout_main_fragmentContainer, Firstfragment()).
addToBackStack("first").commit();
Upvotes: 1