0

I'm creating LoginActivity-> OtherActivity-> Fragment 1-> Fragment_2. When I click Back Button I'm back in Fragment_1 when again I click BackButton I'm in LoginActivity why?

I want come back to MainActivity after the click BackButton in Fragment _1 and after next click BackButton (in MainActivity) I want come back to home screen

How can I do this ?

In MainActivity i have:

@Override
    public void onBackPressed() {

        if (getFragmentManager().getBackStackEntryCount() > 0 ) {
            getFragmentManager().popBackStack();
        } else {
            super.onBackPressed();
        }
    }
SpeedClimber
  • 29
  • 1
  • 7

2 Answers2

0

Call addToBackStack when adding fragment. For example:

FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment);
ft.addToBackStack(backStateName);
ft.commit();

Also, call finish() on your LoginActivity before starting OtherActivity.

ahomphophone
  • 319
  • 1
  • 8
0

At first remove LoginActivity from stack when navigating to OtherActivity. After that use @ahomphophone's answer when presenting fragment. After that back stack should work as expected without needing override 'onBackPressed'.

Note: There is no MainActivity on your provided stack.

Update: If you want to stay in OtherActivity use this code

@Override
public void onBackPressed() {

    if (getFragmentManager().getBackStackEntryCount() > 0 ) {
        getFragmentManager().popBackStack();
    }
}
Vigen
  • 483
  • 6
  • 12
  • How I can remove LoginActivity from stack ? I'm creating MainActivity like this: startActivity(new Intent(getApplicationContext(), MainActivity.class)); Thanks – SpeedClimber Mar 15 '18 at 19:15
  • use this https://stackoverflow.com/questions/1898886/removing-an-activity-from-the-history-stack#answer-4376616 or https://stackoverflow.com/questions/1898886/removing-an-activity-from-the-history-stack#answer-32576294 – Vigen Mar 15 '18 at 19:21
  • I understand but when I add android:noHistory="true" to LoginActivity and I come back to application again I have LoginActivity it's look like I finish my application – SpeedClimber Mar 15 '18 at 19:35
  • When you press back first time your fragment2 popped from stack, the second time fragment1 (and OtherActivity with it) popped from stack. As there is no other Activity in the stack application finishes. If you want to pop only fragment1 the second time (without OtherActivity) you need to override onBackPressed. I will update answer – Vigen Mar 15 '18 at 20:00