Пустой фрагмент при перезагрузке - PullRequest
0 голосов
/ 10 июля 2019

По сути, у меня есть 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;
    }
}

1 Ответ

1 голос
/ 10 июля 2019

Вы должны использовать getChildFragmentManager() для отображения фрагментов внутри фрагментов:

private void replace(Fragment fragmentToReplace, int container) {
    FragmentTransaction ft = getChildFragmentManager().beginTransaction();
    ft.replace(container, fragmentToReplace);
    ft.commit();
}

Так как это гарантирует, что фрагменты обрабатываются должным образом при изменении состояния родителя (т. Е. Когда он заменяется другим фрагментом)и назад).Когда вы используете getActivity.getSupportFragmentManager(), фрагменты не знают, что эти фрагменты связаны, и не могут восстановить фрагменты.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...