Reputation: 4023
May be the title of the question is not clear . Or I have failed to describe what I am looking for .
I have two activity in my app . Lets say their name is "ActivityA" and "ActivityB" . Under "ActivityA" there are few fragments . Lets say their name is "FragmentA" "FragmentB" "FragmentC" "FragmentD" etc . The default fragment is "FragmentA" , that means when the activity starts "FragmentA" starts .
Now , if I navigate to "ActivityB" , and came back to "ActivityA" , it always open "FragmentA" . But what I want is if I navigate to "FragmentB" , and then navigate to "ActivityB" , and back to "ActivityA" it starts "FragmentA" , but I want "FragmentB" to start ,in which I was beforer
Upvotes: 0
Views: 611
Reputation: 8562
Create a method that returns the last visible fragment
public Fragment getVisibleFragment(){
FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
if(fragments != null){
for(Fragment fragment : fragments){
if(fragment != null && fragment.isVisible())
return fragment;
}
}
return null;
}
Create an instance of Fragment
class and set it to null
Fragment lastVisibleFragment = null;
in onPause
save the last fragment
@Override
protected void onPause() {
super.onPause();
lastVisibleFragment = getVisibleFragment();
}
Then in onResume()
add the last fragment you were in if not null
@Override
protected void onResume() {
super.onResume();
if(lastVisibleFragment !=null){
getSupportFragmentManager().beginTransaction()
.add(yourFrameLayout, lastVisibleFragment)
.commit();
}
else{ //Add first fragment you were adding}
}
Upvotes: 1
Reputation: 4436
You might be restarting ActivityA from ActivityB via startActivity()
instead of finishing ActivityB. If it is so, just finish your ActivityB. Then you will be on the last shown fragment in your ActivityA.
Or you can also use onSaveInstanceState
method to keep trace of your Fragments
. This answer can help you with this.
Or using following with your ActivityA can also solves your issue:
<activity android:name=".ActivityA" android:launchMode="singleTop">
Upvotes: 1
Reputation: 306
Not sure if I understand you correctly, but I think what you need to do is startActivityForResult
when you call your ActivityB. When you press BackButton you provide your necessary information about the fragment to be called and catch these infos in ActivityB's onActivityResult
then navigate to the desired Fragment.
Upvotes: 1