Skip to content

Instantly share code, notes, and snippets.

@vladholubiev
Created February 5, 2015 01:12
Show Gist options
  • Select an option

  • Save vladholubiev/0d2716a36f53a6663632 to your computer and use it in GitHub Desktop.

Select an option

Save vladholubiev/0d2716a36f53a6663632 to your computer and use it in GitHub Desktop.
Method before and after refactoring

Before

public static void addFragment(FragmentTransaction fragmentTransaction, Fragment fragment) {
    if (fragment.isAdded()) {
        for (Fragment aFragment : FragmentsKeeper.getAll()) {
            fragmentTransaction.hide(aFragment);
        }
        fragmentTransaction.show(fragment);
        fragmentTransaction.commit();
    } else {
        for (Fragment aFragment : FragmentsKeeper.getAll()) {
            if (aFragment != fragment) {
                fragmentTransaction.hide(aFragment);
            } else {
                fragmentTransaction.add(R.id.main_container, fragment);
            }
        }
        fragmentTransaction.commit();
    }
}

After

public static void addFragment(FragmentTransaction fragmentTransaction, Fragment fragment) {
    hideNotTargetFragments(fragmentTransaction, fragment);
    if (fragment.isAdded()) {
        fragmentTransaction.show(fragment);
    } else {
        fragmentTransaction.add(R.id.main_container, fragment);
    }
    fragmentTransaction.commit();
}

private static void hideNotTargetFragments(FragmentTransaction fragmentTransaction, Fragment fragment) {
    for (Fragment aFragment : FragmentsKeeper.getAll()) {
        if (aFragment != fragment) {
            fragmentTransaction.hide(aFragment);
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment