我有一个名为rootActivity的活动,其中我有一个rootContainer,我在其中替换片段。
现在,我替换的第一个片段是DashboardFragment。
我现在点击十字架打开一个像这样的新片段...... 现在,当我按下后退按钮时,仪表板片段的内容将丢失。
有人可以帮助我
这是一段视频,展示了真正发生的事情。 https://youtu.be/NobqYUCEZKY
DashboardFragment 的代码(包含标签内的片段)
public class DashboardFragment extends Fragment {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private View rootView;
/**
*
* @param config : For setting up stuff by the given config
* @return
*/
public static DashboardFragment newInstance(Bundle config) {
DashboardFragment fragment = new DashboardFragment();
fragment.setArguments(config);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_dashboard, container, false);
toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
((RootActivity)getActivity()).setSupportActionBar(toolbar);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
return rootView;
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(android.R.drawable.btn_star_big_off);
tabLayout.getTabAt(1).setIcon(android.R.drawable.btn_star_big_on);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
adapter.addFragment(new TrackeesFragment(), "Trackee");
adapter.addFragment(new TrackersFragment(), "Trackers");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
return super.instantiateItem(container, position);
}
@Override
public CharSequence getPageTitle(int position) {
return null;
}
}
}
答案 0 :(得分:3)
尝试更改
中的以下行setupViewPager(ViewPager viewPager) {}
更改
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
要
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());