Jaseem Abbas Jaseem Abbas - 2 months ago 25
Android Question

How to resume child fragments on parent fragment resume

I have a fragment called the

MainFragment
with a
TabLayout
. The
TabLayout
has two tabs with a fragment each. Lets call it
Fragment A
and
Fragment B
.

When I open the
MainFragment
,
Fragment A
and
Fragment B
are populated within the
TabLayout
as expected. When I resume
MainFragment
,
Fragment A
and
Fragment B
are not resumed, and I get two empty tabs.

My
MainFragment
looks like this

@Override
public View onCreateView(
LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.main_fragment, null);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);

Injector.component().inject(this);

setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);

}

private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getFragmentManager());
adapter.addFragment(new FragmentA(), "Fragment A");
adapter.addFragment(new FragmentB(), "Fragment B");
viewPager.setAdapter(adapter);
}


How do I solve this?

Answer

Since the Fragments A & B are child fragments of MainFragment, use getChildFragmentManager() instead of getFragmentManager()

Comments