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>
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.
use
getSupportFragmentManager()
instead of
getFragmentManager()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With