Search code examples
androidandroid-fragmentsandroid-activityfragment-tab-host

helpme with Fragment Android


The idea is this .. I have a screen that shows me a list of people .. I select one of them. And I showed this class

public class SlideTabFragment extends FragmentActivity implements ActionBar.TabListener

It is a (fragment tab) the idea is to show in this fragment two screens (two fragment) one that shows the data of the person and in the other a list of relatives .. The point is that every time I go to each fragment always enters the OnCreate of the fragment and the idea is to just do it once. Since the first time I make a call to a webservice that full information. I call the fragment thus

Fragment fragment ;
            if(i == 0 )
            {
                 fragment = new FoodFragment2();
            }
            else
            {
                 fragment = new FoodFragment();
            }
            // Crear un FoodFragment con el nombre como argumento

            return fragment;

Solution

  • By calling new FoodFragment2() and new FoodFragment() you're creating two new fragments every time!

    Save the fragments that you create into variables, and before creation - check if they already exist, and only of they don't - create them.

    Example:

    public class Play {
        FoodFragment foodFragment;
        FoodFragment2 foodFragment2 ;
    
        public FoodFragment createFragment(int i) {
            if(i == 0) {
                if (null == foodFragment2) {
                    foodFragment2 = new FoodFragment2();                
                }
                fragment = foodFragment2;
            } else {
                if (null == foodFragment) {
                    foodFragment = new FoodFragment();                
                }
                fragment = foodFragment2;
            }        
            return fragment;
        }
    }