Save instance to FragmentTabHost

I have a project where I used a FragmentTabHost with an inner fragment with FragmentTabHost

The main function of FragmentActivity

-FragmentTabHost 
  -TAB 1 - FragmentTabHost 
       -tab 1 Fragment
       -tab 2 Fragment    
  -TAB 2 - Fragment   
  -TAB 3 - FragmentTabHost    
  -TAB 4 - Fragment

      

when I switch tab2 to tab1 in the first TAB1 of the main FragmentTabHost their instances are always rebuilt and I call the API method, but I just want to show the "old" results.

How can I keep an instance of these fragments and not make any additional API requests?

some code snippets:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.tab_layout, container, false);

        mTabHost = (FragmentTabHost) rootView.findViewById(android.R.id.tabhost);

        mTabHost.setup(context, getChildFragmentManager(), R.id.tabContent);
        ......

        mTabHost.addTab(mTabHost.newTabSpec("fragment1").setIndicator(viewLeft),
                FragmentTab1.class, new Bundle(0));

      

UPD1. I tried to add

  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

      

java.lang.IllegalStateException: Cannot save fragments nested in other fragments at android.support.v4.app.Fragment.setRetainInstance (Fragment.java:784)

+3


source to share


1 answer


If you don't want to rebuild any tab instance, just take the API response object as a global variable and do the check onCreateView

YourResponseObject yourResponseObject; // this should be global



if(YourResponseObject == null){
    // Hit API here
}else
{
     InflateYourData(YourResponseObject)
}

      

you will be able to save an instance of the tab.

0


source







All Articles