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 展示新闻信息的优化。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章