10

I'm using the new AppCompatActivity introduced in the AppCompat library version 22.1.

When I extend this Activity, the hardware back button no longer pops the back stack of my Fragments, it closes the Activity instead.

Here is how I'm changing fragments in my activity:

public void changeFragment(Fragment f) {
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_holder, f);
    ft.addToBackStack(null);
    ft.commit();
}

If I change MainActivity extends AppCompatActivity to MainActivity extends Activity the problem goes away and I am able to go backwards through my fragments.

Changing calls to getFragmentManager() to getSupportFragmentManager() results in devices running Android < 5.0 losing the Material theme, which was the main reason for implementing AppCompatActivity in the first place.

The style referenced in my manifest <application android:theme="@style/AppTheme">

<style name="AppTheme" parent="Theme.AppCompat.Light">
    <item name="colorPrimary">@color/primary_material_light</item>
    <item name="colorPrimaryDark">@color/primary_dark_material_light</item>
    <item name="colorAccent">@color/accent_material_light</item>
</style>
howettl
  • 12,419
  • 13
  • 56
  • 91

3 Answers3

10

I was able to resolve this by overriding onBackPressed() in my Activity:

@Override
public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount() > 0) {
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }
}

If anybody has any insight into why this extra step is necessary when using AppCompatActivity I would be interested to know.

howettl
  • 12,419
  • 13
  • 56
  • 91
  • Have you also being able to understand why does if (savedInstanceState != null) {} construct is not called onCreate? I have been able to solve the problem by your code, but the update title is not being called. – Amit Pandey Jul 08 '15 at 14:39
  • This is the wrong answer. See @WoookLiu for the proper one. – Paul Burke Nov 08 '15 at 14:01
  • because you extends "activity or fragmentactivity" you can't do with extends fragment, not resolve question about "how you can call Fragment back" –  Mar 09 '16 at 13:36
8

use getSupportFragmentManager() instead of getFragmentManager()

WoookLiu
  • 402
  • 2
  • 14
-3

Are you extending your app theme from Theme.AppCompat.*?

Pedro Loureiro
  • 11,436
  • 2
  • 31
  • 37