当存在多个片段时,后退按钮导航不起作用

时间:2018-01-30 07:35:43

标签: android android-fragments back

我的代码中有3个片段firstTabFragment,secondTabFragemnt和thirdTabFragment。我在这样的另一个片段中调用这些片段:

// setter method for fragments
public void setFirstTabInstance(FirstTabFragment firstTabFragment){
    this.firstTabFragment = firstTabFragment;
}

public void setThirdTabInstance(ThirdTabFragment thirdTabFragment){
    this.thirdTabFragment = thirdTabFragment;
}

public void setSecondTabInstance(SecondTabFragment secondTabFragment){
    this.secondTabFragment = secondTabFragment;
}   

我正在使用下面给出的setter方法:

public void onClick(View v) {
    switch (v.getId())
    {

        case R.id.viewProfileBack:

            if(firstTabFragment!= null)
                firstTabFragment.popBackStack();
            else if(thirdTabFragment != null)
                thirdTabFragment.popBackStack();             

            Log.e(TAG, "Going back to " + firstTabFragment);
            Log.e(TAG, "Going back to " + thirdTabFragment);
            break;
}  
}  

现在我想添加后退按钮导航行为,以下是代码:

firstTabFragment
<{1>}中的

popBackStack方法如下:

public void popBackStack() {
        FragmentManager fragmentManager = getChildFragmentManager();

        int backStackEntryCount = fragmentManager.getBackStackEntryCount();
        System.out.println(backStackEntryCount);

        if (backStackEntryCount > 0) {
            @SuppressLint("RestrictedApi") Fragment fragment = fragmentManager.getFragments().get(backStackEntryCount - 2);
            if (fragment instanceof PeopleProfileFragment) {
                ((PeopleProfileFragment) fragment).refresh();
            } else if (fragment instanceof OrgStructureFragment) {
                ((OrgStructureFragment) fragment).refresh();

            } else if (fragment instanceof SearchDashboardFragment) {
                ((SearchDashboardFragment) fragment).animateBack();
                ((SearchDashboardFragment) fragment).refreshView();
            } else if (fragment instanceof AddToCircleFragment) {

                ((AddToCircleFragment) fragment).refresh();

                if(recentCircleId!= null)
                    ((AddToCircleFragment) fragment).setRecentCircleId(recentCircleId);
           }
            navigateBack();
        }
        fragmentManager.popBackStack();
    }  
<{1>}中的

thirdTabFragment方法如下:

popBackStack

点击public void popBackStack() { backStack(); } 后,应该转到viewProfileBackfirstTabFragment中定义的方法。但是thirdTabFragmentfirstTabFragment都为空。我不明白为什么他们是空的。非常感谢这里的帮助。

1 个答案:

答案 0 :(得分:2)

你的背包是空的。我认为你不是将片段添加到backstack中。 点击片段使用此

将该片段添加到Backstack
Newfragment firstFragment = new Newfragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.article_fragment, firstFragment)
.addToBackStack(null).commit();