I have a Fragment
MyFragment vith a ViewPager
containing more Fragment
. It works properly the first time I load MyFragment, but if I go back and recreate it, the Fragments
in the ViewPager
are not shown because the method FragmentPagerAdapter.getItem
is not called.
I'm using
What's wrong?
import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
...
public class MyFragment extends Fragment {
private ViewPager pager;
private MyPagerAdapter adapter;
private List<Fragment> fragmentList = new ArrayList<Fragment>();
public MyFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_fragment_layout, container, false);
}
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
indicators = (PagerSlidingIndicator) v.findViewById(R.id.indicators);
pager = (ViewPager) v.findViewById(R.id.pager);
Fragment fragment1 = new Fragment1();
fragmentList.add(fragment1);
Fragment fragment2 = new Fragment2();
fragmentList.add(fragment2);
Fragment fragment3 = new Fragment3();
fragmentList.add(fragment3);
adapter = new IndicatorPagerAdapter(getFragmentManager());
pager.setAdapter(adapter);
}
public class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return fragmentList.size();
}
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
}
}
If you are using nested fragments ("I have a Fragment MyFragment vith a ViewPager containing more Fragment"), you need to use getChildFragmentManager()
, not getFragmentManager()
, when setting up your FragmentPagerAdapter
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With