Skip to content Skip to sidebar Skip to footer

Android Fragment Back Button Overlays Other Fragment And Keeps Active

In my App I have 3 fragments. App Starts with [1], User can only navigate to [2] and then optionally to [3]. Since [3] is deep down, I want [3] to go back to [1] directly. Currentl

Solution 1:

There is an issue on how fragments work. See the following life cycle of the above app:

LifeCycle of the App
start
04-0720:34:46.115: D/Fragment_1(15309): onCreateView Fragment_1
04-0720:34:46.115: D/Fragment_1(15309): onResume Fragment_1
Click to open 204-0720:34:49.148: D/Fragment_1(15309): onPause Fragment_1
04-0720:34:49.148: D/Fragment_2(15309): onCreateView Fragment_2
04-0720:34:49.148: D/Fragment_2(15309): onResume Fragment_2
Click to open 304-0720:34:53.633: D/Fragment_2(15309): onPause Fragment_2
04-0720:34:53.633: D/Fragment_3(15309): onCreateView Fragment_3
04-0720:34:53.633: D/Fragment_3(15309): onResume Fragment_3
back Button. Since 3 is not on backstack, app returns to 1 (not pausing 3)
Here Frag 1 and 3 are running and displayed overlaying!
04-0720:35:03.653: D/Fragment_1(15309): onCreateView Fragment_1
04-0720:35:03.653: D/Fragment_1(15309): onResume Fragment_1
back Button on 1 - App exit
04-0720:35:23.474: D/Fragment_1(15309): onPause Fragment_1
04-0720:35:23.474: D/Fragment_3(15309): onPause Fragment_3

Issue now raised with Google: https://code.google.com/p/android/issues/detail?id=68160

Having this and navigating back and forth will crash the app because the FragmentManager basically pauses and resumes the wrong fragments.

Solution 2:

why not adding every fragments to the backstack? Instead of:

MyNewFragment f=new MyNewFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.container, f).commit();

Try:

MyNewFragment f=new MyNewFragment();
getSupportFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.container, f).commit();

Post a Comment for "Android Fragment Back Button Overlays Other Fragment And Keeps Active"