Fragment回退栈

本文介绍了在Android中如何使用FragmentManager进行Fragment的回退栈管理,包括切换Fragment、回滚事务以及清空回退栈的方法。通过事务处理,可以实现Fragment之间的隐藏、显示及动画效果,并能控制回退栈的状态。
摘要由CSDN通过智能技术生成

所谓的回退栈管理其实就是将事务添加到栈中,每次popBackStack返回之前的状态。事务回滚。


    /**
     * 跳转到特定的 Fragment
     *
     * @param containerViewId fragment 容器 id
     * @param fragment        对象
     * @param tag             标识
     */
    public void switchToFragment(int containerViewId, Fragment fragment, String tag) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        List<Fragment> currentFragments = getSupportFragmentManager().getFragments();

        // 不是第一个 fragment 时,设置转场动画,隐藏上一个 fragment,并将其加入返回栈中
        if (currentFragments.size() != 0) {
            ft.setCustomAnimations(R.anim.push_in_from_right, R.anim.push_out_to_left,
                    R.anim.push_in_from_left, R.anim.push_out_to_right);
            Fragment currentFragment = currentFragments.get(currentFragments.size() - 1);
            ft.hide(currentFragment).addToBackStack(currentFragment.getTag());
        }

        if (fragment.isAdded()) {
            ft.show(fragment);
        } else {
            ft.add(containerViewId, fragment, tag);
        }

        ft.commit();
    }

    /**
     * 直接回到栈底,清空 Fragment 回退栈
     */
    public void clearFragmentBackStack() {
        FragmentManager fm = getSupportFragmentManager();
        int count = getSupportFragmentManager().getBackStackEntryCount();
        for (int i = 0; i < count; ++i) {
            fm.popBackStackImmediate();
        }
    }

如上管理,添加第一个Fragment时 Fragment1可见
添加第二个Fragment时 Fragment1隐藏,显示Fragment2 事务添加到回退栈.
添加第三个Fragment时 Fragment2隐藏,显示Fragment3 事务添加到回退栈.

值得注意的是,一次commit()所有操作作为一次事务添加到回退栈。如上,hideadd作为一次事务。

此时int count = getSupportFragmentManager().getBackStackEntryCount(); 为2,所以clearFragmentBackStack()直接回退到Fragment1可见的状态。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值