findFragmentByTag切换选项卡上的奇怪行为

时间:2014-10-08 07:40:10

标签: android android-fragments tabs android-actionbar fragmenttransaction

我有5个片段,我在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();
}

然后在一个函数中我想从Fragment4中获取一个值:

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

问题是当我在tab 4上是我的Fragment4内容页面时,findFragmentByTag的返回始终为null但是当我切换到另一个选项卡时,然后找到Fragment它返回true Fragment而不是null。 为什么会这样?我该如何解决这个问题?在此先感谢。

1 个答案:

答案 0 :(得分:1)

进行测试...

变化

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

通过

int tag = getActionBar().getSelectedNavigationIndex();