Lucas P. Lucas P. - 1 month ago 6
Android Question

Pressing back on last fragment shows blank Activity shortly before going to previous Activity

I have two

Activities
and each one has 3-4
Fragments
that each replace the other one.

When
Activity1
,
Fragment2
launches the second activity,
Activity2
,
Fragment1
is launched and
onBackPressed
closes the
Activity2
and goes back to
Activity1
as normally.

When I'm launching
Activity2
from
Activity1
,
Fragment3
though, I want to add
Fragment2
to the 2nd activity, which is done via cone in the
onCreate
method.

However, when the back button is pressed, the fragment disappears for a split second, leaving
Activity2
blank on the screen and after that
Activity2
is closed, resulting in a visual glitch.

Is there anything I can do to close
Activity2
the exact moment (at least at the same visual moment) as when
Fragment2
is being closed by the back button?

Thank you.

P.S.: Not adding the Fragment to the backStack seems to close the activity immediately, which is what happens in the first case (expected behavior), but when adding the Fragment to the backStack (as needed for correct operation in the second case) produces the glitch.

Answer

Ok, after fighting with the backStack for many days, I decided to skip it, since it does not seem to be working properly, or I'm not understanding it.

The way I did it is on my Activity's onBackPressed i'm checking which fragment is showing and if it's the one that should be the last one (Multiple ones are the "last one") I just finish() the Activity.

@Override
public void onBackPressed() {

    MyFragment myFragment = (MyFragment)fragmentManager.findFragmentByTag("MyFragment");
    if (myFragment != null && myFragment .isVisible()) {
        //if myFragment is visible when the back button is pressed...
        finish();
    } else {
        super.onBackPressed();
    }
}

Don't forget to give a name to your fragment in the FragmentManager transaciton. In my case it is "MyFragment".

Comments