I have two fragments in my Activity. One contains a viewpager which also has two fragments in it. Everything works fine but the problem is when i re-visit the fragment containing the viewpager from the other fragment, the child fragments in the viewpager are never shown.
This is the fragment containing the viewpager, MainHistoryFragment.java
public class MainHistoryFragment extends Fragment {
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.activity_hist, container, false);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getActivity(), getActivity().getSupportFragmentManager());
ViewPager viewPager = view.findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = view.findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
tabs.getTabAt(0).setIcon(android.R.drawable.ic_dialog_email);
tabs.getTabAt(1).setIcon(android.R.drawable.ic_menu_compass);
}
}
and this is the class subclassing the FragmentPagerAdapter, SectionsPagerAdapter
public class SectionsPagerAdapter extends FragmentPagerAdapter {
@StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2};
private static final int totalTabs = 2;
private final Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
switch (++position){
case 1:
return new HistoryFragment();
case 2:
return new BookmarkFragment();
default:
return null;
}
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
@Override
public int getCount() {
return totalTabs;
}
}
I noticed that the getItem() method of the SectionsPagerAdapter never gets called after a revisit. Please how do i get my fragments in the viewpager to show after a revisit?
Change this line:
to:
You need to use getChildFragmentManager() when u are adding another fragment inside a fragment.
Hope this helps! Happy Coding!