初始化和切换Fragment

初始化:

/**
    初始化Fragment并将Fragment添加到fragments中,此处的fragments是一个Fragment的列表
     private List fragments;
     */
    private void initFragments() {
        fragments = new ArrayList<>();
        fragments.add(new NewsFragment());
        fragments.add(new BlogFragment());
        fragments.add(new FindFragment());
        fragments.add(new MyFragment());

    }

切换:

 /**
     * 切换fragment
     */
    private void switchFragments(int index) {
        FragmentTransaction fragmentTransaction = this.getSupportFragmentManager().beginTransaction();
        for (int i = 0; i < fragments.size(); i++) {
            Fragment fragment = fragments.get(i);
            if (i == index) {//显示fragment
                if (fragment.isAdded()) {//如果当前fragment已经创建,直接显示fragment
                    fragmentTransaction.show(fragment);
                } else {//第一创建fragment, 将fragment放入到容器中
                    fragmentTransaction.add(R.id.fl_container, fragment);
                }
            } else {//隐藏剩余fragment
                if (fragment.isAdded()) {
                    fragmentTransaction.hide(fragment);
                }
            }
        }

        fragmentTransaction.commitNowAllowingStateLoss();
    }

你可能感兴趣的:(Android开发)