4

I have fragments in stack like Main frag --> A frag --> B frag --> C frag --> D frag.

How can I go back to main fragment from any of A, B, C, D fragment. For eg: if i clicked button in D, I should be back to Main fragment. Same should happen in case of button click on fragment C. And, on back button click from Main fragment, it should not go back to Fragment D or C.

I tried to pop out all fragment from stack & start again from main fragment. But it doesn't work.

 private void onButtonClick(){
    MainFragment mainFrag= new MainFragment();
    getActivity().getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);//pop back stack inclusive pops all fragment
    getActivity().getSupportFragmentManager().beginTransaction().add(R.id.mainFragment, mainFragment).addToBackStack(null).commit();
}

Edit : Ok, it looks like above code is going back to main fragment. But after showing Main fragment for a second, the app minimizes. After main fragment minimizes, following log is shown on Android logcat.

V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 570

V/FA: Activity paused, time: 14995077

V/FA: Inactivity, disconnecting from the service

Binod Lama
  • 226
  • 5
  • 24

2 Answers2

1

If MainActivity is your frameLayout place , here is my answer:

//just add a switch method on your activity
public void switchFragment(Fragment fragment) {
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(R.id.mainFrame, fragment, null);
    transaction.addToBackStack(null);
    transaction.commit();
}

and use it in any fragments for your button like this:

private void onButtonClick(){
    (MainActivity)getActivity()).switchFragment(new the fragment));
  }

Hope it can help~

Morton
  • 5,380
  • 18
  • 63
  • 118
  • Thanks for answer. But I also want to clear the backstack before switching fragment. So I can stop going to previous fragment on back press. So, I used FragmentManager.POP_BACK_STACK_INCLUSIVE. But it is minimizing the app. Any idea, how to prevent going back to previous fragment? – Binod Lama May 31 '17 at 10:26
  • If i want to prevent going back to previous fragment i will remove this code `transaction.addToBackStack(null);` on my switchFragment method . Hope it still can help you. – Morton Jun 01 '17 at 01:05
0
getSupportFragmentManager().popBackStackImmediate(mainFragment.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
Orest Savchak
  • 4,529
  • 1
  • 18
  • 27