0

I have three tabs inside viewpager using FragmentPagerAdapter.

here is my top level fragment which holds viewpager

public class TabHolderFragment extends Fragment {

View view;
ViewPager viewPager;
TabLayout tabLayout;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.tab_holder_fragment, container, false);
    viewPager = (ViewPager) view.findViewById(R.id.viewpager);
    viewPager.setOffscreenPageLimit(2);
    viewPager.setAdapter(new SectionsPagerAdapter(getChildFragmentManager()));
    tabLayout = (TabLayout) view.findViewById(R.id.sliding_tabs);
    tabLayout.post(new Runnable() {
        @Override
        public void run() {
            tabLayout.setupWithViewPager(viewPager);
        }
    });

    return view;
}
}

this is my adapter class

public class SectionsPagerAdapter extends FragmentPagerAdapter  {

public SectionsPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {
    //Fragment fragment;
    switch (position){
        case 0:
            return new TabTimeline();
        case 1:
            return new TabMyPosts();
        case 2:
            return new TabNotifications();
        default:
            return new TabTimeline();
    }

}


@Override
public int getCount() {
    // Show 3 total pages.
    return 3;
}

@Override
public CharSequence getPageTitle(int position) {
    switch (position) {
        case 0:
            return "Timeline";
        case 1:
            return "My Posts";
        case 2:
            return "Notifications";
    }
    return null;
}
}

My problem is all lifecycle functions runs twice on orientation change, and onPause and onResume runs twice when app goes background. i go through many stackoverflow questions but nothing work for me (or i didn't understand clearly).

Please Help.

Hareesh
  • 6,770
  • 4
  • 33
  • 60
  • When `Fragments` do things too many times, it is usually due to the system recreating them and the programmer recreating them. I believe that `ViewPager` will automatically recreated fragments in orientation change. Are you checking to make sure the fragments don't already exist? See this Stack Overflow [question](http://stackoverflow.com/questions/32478968/android-viewpager-orientation-change) and answer. – Cheticamp Mar 28 '17 at 15:18
  • `setRetainInstance(true)` has no effect. Before adding fragment to MainActivity i check for `savedInstanceState` now my tabs retains position on rotation correctly. But when app goes background and resumes `onPause`,`onResume `and `onSaveInstanceState` runs twice, and values i saved in `onSaveInstanceState` resets.any idea? – Hareesh Mar 28 '17 at 17:51

0 Answers0