Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment back stack does not work when extending AppCompatActivity

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>
like image 958
howettl Avatar asked Apr 22 '15 03:04

howettl


2 Answers

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.

like image 63
howettl Avatar answered Nov 15 '22 23:11

howettl


use getSupportFragmentManager() instead of getFragmentManager()

like image 8
WoookLiu Avatar answered Nov 15 '22 21:11

WoookLiu