Separate Back Stack for each tab in Android using Fragments

后端 未结 12 1018
南旧
南旧 2020-11-22 14:51

I\'m trying to implement tabs for navigation in an Android app. Since TabActivity and ActivityGroup are deprecated I would like to implement it using Fragments instead.

12条回答
  •  一个人的身影
    2020-11-22 15:20

    A simple solution:

    Every time you change tab/root view call:

    fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    

    It will clear the BackStack. Remember to call this before you change the root fragment.

    And add fragments with this:

    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    NewsDetailsFragment newsDetailsFragment = NewsDetailsFragment.newInstance(newsId);
    transaction.add(R.id.content_frame, newsDetailsFragment).addToBackStack(null).commit();
    

    Note the .addToBackStack(null) and the transaction.add could e.g. be changed with transaction.replace.

提交回复
热议问题