0

So I have four fragments (A,B,C and D). I use buttons to navigate between them and if I for example go from A to B and from B to A it loads A again and I don't want it to happen.

This is a code I'm calling to load fragment into container :

public void showNewFragment(Class<? extends Fragment> fragmentClass, Integer whereToPlaceId, Bundle bundle)
    {
        String tag = fragmentClass.getSimpleName();


        FragmentManager fm = getSupportFragmentManager();
        boolean inStack = fm.popBackStackImmediate(tag,0);



        FragmentTransaction fragTM = fm.beginTransaction();


        if(!inStack) {

            try {
                fragTM.add(whereToPlaceId, fragmentClass.newInstance(), tag);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        fragTM.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        fragTM.addToBackStack(tag);
        fragTM.commit();
    }

Also I tried with onSaveInstanceState but it's only called when config change is made.

Also in activity which holds this fragments I disabled back button navigation.

EDIT :

I did this in my fragment

    public static View rootView = null;
    
     @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
    
                if(rootView != null)
                    return rootView;
                //if not init rootView

                return rootView;
}

Is this good approach ?

Community
  • 1
  • 1
  • check [this post](http://stackoverflow.com/questions/11353075/how-can-i-maintain-fragment-state-when-added-to-the-back-stack) – Dan Chaltiel Nov 25 '15 at 10:00
  • @DanChaltiel I edited my question with solution that work but I don't know is this good solution or not.What do you say ? – Haris Kovacevic Nov 25 '15 at 10:37
  • That is called a singleton pattern, its a common thing. – Nanoc Nov 25 '15 at 10:46
  • @Nanoc I know how it's called but I mean is it good in terms of performance of application and memory usage ? – Haris Kovacevic Nov 25 '15 at 12:50
  • Well i would never store a view in a static, and i cant see why are you doing it instead of inflating the view every time, this should be better for performance since you only inflate it one time, but worse for memory since you store it statically. – Nanoc Nov 25 '15 at 13:06

0 Answers0