Simplified Fragment Navigation, using a custom backstack and commitNow()*

Why is the Activity backstack bad?

from http://stackoverflow.com/a/24157802/2413303

Why is the Fragment backstack bad?

from http://hahack.com/wiki/android-fragment.html
@Override
public void commitNow() {
disallowAddToBackStack();
mManager.execSingleAction(this, false);
}

What people forgot to tell you about the FragmentManager

Managing a backstack of keys that identify Fragments

Our weapon of choice

Flow history manipulation
Simple-Stack history manipulation

Identifying the Fragments in our custom backstack

public interface Key extends Parcelable {
Fragment newFragment();
String getFragmentTag();
}

Managing the Fragments inside the FragmentManager according to the currently active keys

begin fragment transaction
disallow adding to backstack (commitNow would not work otherwise)
animate the fragments according to state change direction
for all keys in the previous state
if the fragment associated with key exists
then if it is not found in the new state, remove it
otherwise if it is not yet detached, then detach it
for all keys in the new state
if the fragment is the new active state
then if it exists,
if it's removing, then create and replace it
if it's detached, then attach it
else if it does not exist, then create and add it
if it is not the new active state,
then if it exists and is not yet detached, then detach it
commit fragment transaction now

Some examples

Conclusion

Coordinators example rewritten with Fragments

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store