Android - 如何在替换另一个片段之前保存片段的状态?

时间:2014-05-12 14:16:57

标签: android android-fragments

我在片段“A”调用中从服务器获取数据。当我用“B”替换“A”时,从“B”返回“A”后,每次调用片段“A”,因此每次都会生成HTTPGET。如何避免这种情况并在活动中重用像REORDER_TO_FRONT这样的片段?

我使用此代码替换为新片段

FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();
transaction.replace(R.id.rl_fragment_content, newFragment,
                backStackName);
transaction.addToBackStack(backStackName);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        transaction.commit();

当我背压时,

  Fragment fragment = null;
        fragment = getSupportFragmentManager().findFragmentByTag(
                    "some_fragment_name");
        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();

        transaction.replace(R.id.rl_fragment_content, fragment);
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        transaction.addToBackStack("some_fragment_name");
        transaction.commit();

2 个答案:

答案 0 :(得分:6)

使用

阻止您的片段重新充气视图
if (view != null) {
//this will prevent the fragment from re-inflating(when you come back from B) 
            ViewGroup parent = (ViewGroup) view.getParent();
            parent.removeView(view);
        } else {
//inflate the view and do what you done in onCreateView()
        }

答案 1 :(得分:1)

有几种方法可以做到这一点,但最简单的方法是在片段上使用添加和隐藏而不是替换。此代码(未经测试)将显示newFragment2并将newFragment1添加到backstack。在你的backstack代码中将显示newFragment1并将任何你想要的内容添加到backstack

FragmentTransaction transaction = getSupportFragmentManager()
            .beginTransaction();
transaction.add(R.id.rl_fragment_content, newFragment1,
            backStackName1); //now you have an instance of newFragment1
transaction.add(R.id.rl_fragment_content, newFragment2,
            backStackName2); //now you have an instance of newFragment2
transaction.addToBackStack(backStackName1);
transaction.show(newFragment2);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();

以后

Fragment fragment = null;
fragment = getSupportFragmentManager().findFragmentByTag(
            backStackName1);
FragmentTransaction transaction = getSupportFragmentManager()
        .beginTransaction();

transaction.show(fragment)
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.addToBackStack("whatever_you_want");
transaction.commit();

请注意,这将保留视图。如果您想在屏幕旋转之间保持不变,则需要在主机Activity中实现Bundle。