fragment界面切换

private List fragments;


fragments = new ArrayList<>();
        //添加要切换的fragment
        fragments.add(new HomeUserFragment());
        fragments.add(new SpotCheckFragment());
        fragments.add(new AndonFragment());
        fragments.add(new FileFragment());
        fragments.add(new NoticeFragment());

showfragmentByIndex(0) :初始化显示首页

//切换界面
    public void showFragmentByIndex(int index) {
        for (int i = 0; i < fragments.size(); i++) {
            if (i == index) {
                if (fragments.get(i).isAdded()) {
                    getSupportFragmentManager().beginTransaction().show(fragments.get(i)).commitAllowingStateLoss();
                    getSupportFragmentManager().executePendingTransactions();
                } else {
                    getSupportFragmentManager().beginTransaction().add(R.id.activity_main_fragment, fragments.get(i)).commitAllowingStateLoss();
                    getSupportFragmentManager().executePendingTransactions();
                }
            } else {
                if (fragments.get(i).isAdded()) {
                    getSupportFragmentManager().beginTransaction().hide(fragments.get(i)).commitAllowingStateLoss();
                    getSupportFragmentManager().executePendingTransactions();
                }
            }
        }
    }

至于FragmentTransaction的commit和commitAllowingStateLoss的区别:

推荐 https://blog.csdn.net/stoppig/article/details/31776607

 

你可能感兴趣的:(fragment界面切换)