1

I have lots of Fragments and two activities one is main activity that holds every fragments. When i am going to second activity from any fragment its work fine but after that i am pressing back button for come back to my last added fragment in this case i come to home screen . I must have the second activity I can't replace that by fragment.How to come back to the last fragment from activity?

In one more case i must have go to the browser and at browser by pressing back button app directly goes to home screen so how to prevent this ?

3 Answers3

1

When you back pressed from second activity then onResume() of first activity will be called.So you have manage it from onResume(),check last fragment in back stack and move to that fragment.

So you have to use this code in your onResume() of first activity

FragmentManager manager = getSupportFragmentManager();
int count = manager.getBackStackEntryCount();
if(count>0){
  Fragment  mfragment = manager.getBackStackEntryAt(count-1);
  FragmentTransaction ft = fragmentManager.beginTransaction();
  ft.replace(R.id.content_frame, mFragment);
  ft.commit();
}
Ravi Bhandari
  • 4,682
  • 8
  • 40
  • 68
  • Hi, Thanks for your response I checked the onResume() of first activity but on pressing back button from second activity onResume() of first activity is not called and app directly goes to the home screen :( – user3279650 Feb 06 '14 at 14:22
  • please share your code what are you doing.because if you click back button from Activity B then onResume() of Activity A will be called and it is working for me. – Ravi Bhandari Feb 07 '14 at 05:22
  • Hi, Thanks for your response but i can't share my code because the code is too large and activity A holds 15 fragments and i go to any fragment from any fragment so i am sorry and when i press the back button from activity B then the onDestroy() method call of activity A and app will be closed. – user3279650 Feb 08 '14 at 05:52
0

you can use:

getSupportFragmentManager().popBackStack();
deadfish
  • 11,996
  • 12
  • 87
  • 136