再次查看时,Viewpager中的片段不显示

时间:2019-12-18 13:24:08

标签: android android-fragments android-viewpager fragment fragmentpageradapter

我的活动中有两个片段。一个包含一个viewpager,其中也有两个片段。一切正常,但问题是当我从另一个片段重新访问包含viewpager的片段时,从不显示viewpager中的子片段。

这是包含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);
}

}

这是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;
}

}

我注意到,SectionsPagerAdapter的getItem()方法在重新访问后再也不会被调用。 请问如何在重新访问后将片段显示在viewpager中?

1 个答案:

答案 0 :(得分:0)

更改此行:

SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getActivity(), getActivity().getSupportFragmentManager());

收件人:

SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getActivity(), getActivity().getChildFragmentManager());

当您在片段中添加另一个片段时,需要使用getChildFragmentManager()。

希望这会有所帮助!编码愉快!