Fragment addToBackStack(null)的作用

Fragment常用于一个activity中展示多个相对独立的部分,利用add,show,hide进行fragment的添加,展示和隐藏。

 FragmentA fragmentA = FragmentA .newInstance(parameter);
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.place_holder_view, fragmentA )
                        .show(goodsDetailFragment)
                        .commitAllowingStateLoss();
                        
 getSupportFragmentManager().beginTransaction().hide(fragmentA )
                        .add(R.id.place_holder_view, fragmentB )
                        .commitAllowingStateLoss();

.add(R.id.place_holder_view, fragmentB )可以显示fragment,此时点击手机的back键,会回调Activity的onBackPressed()函数,此时会直接关闭activity。
如果添加fragment时使用了 .addToBackStack(null),会将Fragment添加到回退栈中,有什么作用呢?此时点击back键,回调Activity的onBackPressed()函数会把当前展示的fragment弹出回退栈,展示前面添加的fragment。fragmentB.isAdded()显示为false,没有被添加,所以此时无法调用show函数使fragmentB展示。

 FragmentA fragmentA = FragmentA .newInstance(parameter);
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.place_holder_view, fragmentA )
                        .addToBackStack(null)
                        .show(goodsDetailFragment)
                        .commitAllowingStateLoss();

此时可以重写onBackPressed()函数,自己用代码hide,show相应的fragment。

//添加add之后,利用hide。show展示相应的已添加的fragment,此时不会重建fragment,只会走 onHiddenChanged(boolean hidden) 函数
 getSupportFragmentManager().beginTransaction().hide(fragmentA)
                        .show(fragmentB).commitAllowingStateLoss();

工作这两三年用了太多的fragment,有时间会写一下列表fragment配合viewpager 展示新闻信息的优化。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值