我的问题是similtar:
Android ViewPager Inside Fragment Loaded Only Once
不同之处在于它的答案对我不起作用。
我有4个片段。在其中一个片段中,有一个片段X ,ViewPager
可以切换到另外两个片段。我第一次加载FragmentX
时ViewPager
正常工作。问题是如果我切换到其他4个片段中的一个,当我回到FragmentX
时,ViewPager
内部没有任何内容。
片段X
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_campus, container, false);
TabLayout tabLayout = (TabLayout)view.findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Mapa"));
tabLayout.addTab(tabLayout.newTab().setText("Eventos"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
vpPager = (ViewPager)view.findViewById(R.id.vpPager);
adapterViewPager = new PagerAdapter(getChildFragmentManager());
vpPager.setAdapter(adapterViewPager);
vpPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
vpPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
PageAdapter
public class PagerAdapter extends FragmentPagerAdapter {
private int NUM_ITEMS = 2;
public PagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
@Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return MapFragment.newInstance(0);
case 1:
return EventosFragment.newInstance(1);
default:
return null;
}
}
// Returns the page title for the top indicator
@Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
}
MainActivity
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
...
if (...) {
if (campusFragment == null) // the problem is not solved by commenting this condition
campusFragment = new CampusFragment(); // Fragment X
fragmentManager.beginTransaction().replace(R.id.content_frame, campusFragment).commit();
}
}