How to prevent fragments from multiple instance

private void replaceFragment (Fragment fragment){
  String backStateName = fragment.getClass().getName();

  FragmentManager manager = getSupportFragmentManager();
  boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);

  if (!fragmentPopped){ //fragment not in back stack, create it.
    FragmentTransaction ft = manager.beginTransaction();
    ft.replace(R.id.content_frame, fragment);
    ft.addToBackStack(backStateName);
    ft.commit();
  }
}


For my case:
I have declared it in  a class 

public static void replaceFragment (FragmentManager manager,Fragment fragment){

    String backStateName =  fragment.getClass().getName();
    String fragmentTag = backStateName;
    boolean fragmentPopped = manager.popBackStackImmediate(backStateName, 0);
    if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null) { //fragment not in back stack, create it.
        FragmentTransaction ft = manager.beginTransaction();
        ft.replace(R.id.fragmentContainer, fragment, fragmentTag);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        ft.addToBackStack(backStateName);
        ft.commit();

    }
}

and used it as :

Functions.replaceFragment(getFragmentManager(),new OrderFoodTypeFragment());

Reference :

http://stackoverflow.com/questions/18305945/how-to-resume-fragment-from-backstack-if-exists/18306258#18306258

Advertisements

মন্তব্য করুন

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  পরিবর্তন )

Google+ photo

You are commenting using your Google+ account. Log Out /  পরিবর্তন )

Twitter picture

You are commenting using your Twitter account. Log Out /  পরিবর্তন )

Facebook photo

You are commenting using your Facebook account. Log Out /  পরিবর্তন )

w

Connecting to %s