Android Action Bar tabs - inner fragment transaction issues

前端 未结 1 796
北海茫月
北海茫月 2021-02-09 18:09

I have successfully set up tabs in the Action Bar using the following example from Google themselves at http://developer.android.com/resources/samples/ApiDemos/src/com/example/a

相关标签:
1条回答
  • 2021-02-09 19:05

    Ok, so this answer assumes you want to wipe each tabs back history every time you swap tabs. What I mean by that is Tab 1 starts on frag 1, then you click and change it to frag 2. If you select Tab 2, you will be undoing the history of Tab 1 and next time you click Tab 1 you will be back to frag 1.

    With that said here is the solution: Replace your onTabUnselected with the below

    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            if (mFragment != null) {
                //this segment removes the back history of everything in the tab you are leaving so when you click on the tab again you go back to a fresh start
                FragmentManager man = mActivity.getFragmentManager();
                if(man.getBackStackEntryCount()>0) //this check is required to prevent null point exceptions when clicking off of a tab with no history
                    man.popBackStack(man.getBackStackEntryAt(0).getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE); //this pops the stack back to index 0 so you can then detach and then later attach your initial fragment
                //also it should be noted that if you do popbackstackimmediate here instead of just popbackstack you will see a flash as the gui changes back to the first fragment when the code executes
                //end
                ft.detach(mFragment);
            }
        }
    
    0 讨论(0)
提交回复
热议问题