基本上,我有一个MainActivity
,当单击菜单选项时会显示不同的片段。
Stats
是Fragment
,其中显示4个片段。每次显示时,都会在视图上替换4 FrameLayouts
。
第一次可以完美运行,但是当我换成不同的片段并返回统计信息时,似乎并没有将FrameLayouts
替换为Fragments
...
Stats
如下:
public class StatsFragment extends Fragment {
private View rootView;
private MoreSoldBarChartFragment moreSold = MoreSoldBarChartFragment.newInstance(null);
private MoreIncomeBarChartFragment moreIncome = MoreIncomeBarChartFragment.newInstance(null);
private SoldLineChartFragment soldLine = SoldLineChartFragment.newInstance(null);
private IncomeLineChartFragment incomeLine = IncomeLineChartFragment.newInstance(null);
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_stats, container, false);
initViews();
return rootView;
}
public void initViews() {
replace(moreIncome, R.id.moreIncome);
replace(moreSold, R.id.moreSold);
replace(soldLine, R.id.soldLine);
replace(incomeLine, R.id.incomeLine);
}
private void replace(Fragment fragmentToReplace, int container) {
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(container, fragmentToReplace);
ft.commit();
}
public static StatsFragment newInstance(Bundle args) {
StatsFragment fragment = new StatsFragment();
fragment.setHasOptionsMenu(true);
fragment.setArguments(args);
return fragment;
}
}
答案 0 :(得分:1)
您应该使用getChildFragmentManager()
在“片段”中显示片段:
private void replace(Fragment fragmentToReplace, int container) {
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(container, fragmentToReplace);
ft.commit();
}
这样可以确保在更改父项的状态时(即,在将其与另一个Fragment交换并返回时)正确处理Fragments。当您使用getActivity.getSupportFragmentManager()
时,片段不知道这些片段是相关的,并且无法还原这些片段。