Avoid recreating same view when perform tab switching

后端 未结 6 590
一生所求
一生所求 2021-01-30 17:43

Current, I have 2 Fragments, which is switch-able through ActionBar\'s tab.

    getSupportActionBar().setNavigationMode(ActionBar.NAVIG         


        
6条回答
  •  南方客
    南方客 (楼主)
    2021-01-30 17:44

    I started searching for a simple solution for this many hours ago and finally stumbled across the answer by @roger which saved me lots of hair....

    When using the ViewPager in other implementations, I could simply call:

    mViewPager.setOffscreenPageLimit(//number of pages to cache);
    

    So, I was very surprised it took me so many hours to resolve this. The example he gave wasn't entirely clear though, so for the sake of completeness, here is the code I use for the Fragments in my FragmentTabHost

    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    public class FragmentExample extends Fragment {
    
        private View rootView;
    
        public FragmentExample() {
        }
    
        @Override
        public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
    
            if (rootView == null) {
    
                rootView = inflater.inflate(R.layout.fragment_example_layout, container, false);
    
                // Initialise your layout here
    
            } else {
                ((ViewGroup) rootView.getParent()).removeView(rootView);
            }
    
            return rootView;
        }
    }
    

    I searched for the following key phrases which I'm adding here, in the hope that I may save someone else from the frustration I've just experienced!


    FragmentTabHost save Fragment state

    FragmentTabHost views recreated

    FragmentTabHost cache Fragments

    FragmentTabHost onCreateView Fragment destroyed


提交回复
热议问题