How to keep only first added Fragment in back stack (fragment overlapping)?

前端 未结 5 1986
盖世英雄少女心
盖世英雄少女心 2020-12-03 18:06

Scenario what i\'m trying to achieve:

  1. Loading activity with two frame containers (for list of items and for details).
  2. At the app launch time add listF
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 19:05

    Very nice explanation by Budius. I read his advice and implemented similar navigation, which I would like to share with others.

    Instead of replacing fragments like this:

    Transaction.remove(detail1).add(detail2)
    Transaction.remove(detail2).add(detail3)
    Transaction.remove(detail3).add(detail4)
    

    I added a fragment container layout in the activity layout file. It can be either LinearLayout, RelativeLayot or FrameLayout etc.. So in the activity on create I had this:

    transaction.replace(R.id.HomeInputFragment, mainHomeFragment).commit();
    

    mainHomeFragment is the fragment I want to get back to when pressing the back button, like infoFrag. Then, before EVERY NEXT transaction I put:

    fragmentManager.popBackStackImmediate();
    transaction.replace(R.id.HomeInputFragment, frag2).addToBackStack(null).commit();
    

    or

    fragmentManager.popBackStackImmediate();
    transaction.replace(R.id.HomeInputFragment, frag3).addToBackStack(null).commit();
    

    That way you don't have to keep track of which fragment is currenty showing.

提交回复
热议问题