0
\$\begingroup\$

I use this code to check a fragment before showing it. What can you say about it?

int backStackEntryCount = getFragmentManager().getBackStackEntryCount();
if (backStackEntryCount > 0){
    String newFragmentTag = fragment.getClass().getSimpleName()+"|"+fragment.getArguments();
    String nowShowFragmentTag = getFragmentManager().findFragmentById(R.id.main_activity_fragment_container).getTag();
    if (!newFragmentTag.equals(nowShowFragmentTag)) {
        getFragmentManager()
                .beginTransaction()
                .replace(R.id.main_activity_fragment_container, fragment, fragment.getClass().getSimpleName()+"|"+fragment.getArguments())
                .addToBackStack(fragment.toString())
                .commit();
    }
}
\$\endgroup\$
2
\$\begingroup\$
  • In this line:

    .replace(R.id.main_activity_fragment_container, fragment, fragment.getClass().getSimpleName()+"|"+fragment.getArguments())
    

    you can reuse the newFragmentTag variable:

    .replace(R.id.main_activity_fragment_container, fragment, newFragmentTag)
    

    This way you don't have to perform the same string concatenation twice, which is sort of the purpose of variables & methods in the first place.

  • Try to use getSupportFragmentManager() if you're using AppCompatActivity.

  • Since you're going to replace the fragment in R.id.main_activity_fragment_container anyways, there's no need to check the back stack. Just check if there are any fragments in the container before checking its tag.


Below is how I would rewrite the code in my style (you don't have to follow this):

FragmentManager fManager = getSupportFragmentManager();
String newFragmentTag = fragment.getClass().getSimpleName() + "  |  " + fragment.getArguments();

Fragment currentFragment = fManager.findFragmentById(R.id.main_activity_fragment_container);
if (currentFragment != null && currentFragment.getTag().equals(newFragmentTag)) {
    Log.w(TAG, "Fragment is already displayed");
    return;
}

fManager
    .beginTransaction()
    .replace(R.id.main_activity_fragment_container, fragment, newFragmentTag)
    .addToBackStack(fragment.toString())
    .commit();
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.