Search code examples
androidandroid-fragmentstabsandroid-actionbarfragmenttransaction

findFragmentByTag Strange behavior on Switching Tabs


I have 5 fragments which i switch between them in ActionBar :

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) 
{
    int tag = (Integer) tab.getTag();
    fragmentTransaction = fragmentManager.beginTransaction();

    switch(tag)
    {
    case 0:
        FragmentBase fragBase = new FragmentBase ();
        fragmentTransaction.replace(R.id.frame_order,fragBase,"FragmentBase");
        fragmentTransaction.addToBackStack(null);
        break;

    case 1:
        Fragment1 frag1 = new Fragment1();
        fragmentTransaction.replace(R.id.frame_order, frag1, "Fragment1");
        fragmentTransaction.addToBackStack(null);
        break;

    case 2:
        Fragment2 frag2 = new Fragment2();
        fragmentTransaction.replace(R.id.frame_order, frag2, "Fragment2");
        fragmentTransaction.addToBackStack(null);
        break;

    case 3:
        Fragment3 frag3 = new Fragment3();
        fragmentTransaction.replace(R.id.frame_order, frag3, "Fragment3");
        fragmentTransaction.addToBackStack(null);
        break;

    case 4:
        Fragment4 frag4 = new Fragment4();
        fragmentTransaction.replace(R.id.frame_order, frag4, "Fragment4");
        fragmentTransaction.addToBackStack(null);
        break;

    }
    fragmentTransaction.commit();
}

then in a function i want to get a value from the Fragment4 :

Fragment4 frag4 = (Fragment4)getSupportFragmentManager().findFragmentByTag("Fragment4");
    String stfrag4 = frag4.getFrag4Value();

the problem is when i'm on tab 4 which is my Fragment4 contents page , the return of findFragmentByTag is always null but when i switch to another tab then find that Fragment it returns true Fragment and not null. why is this happening? and how can i solve the issue? Thanks in Advance.


Solution

  • make test...

    change

    int tag = (Integer) tab.getTag();
    

    by

    int tag = getActionBar().getSelectedNavigationIndex();