保存片段状态?

时间:2015-11-25 09:55:27

标签: android

所以我有四个片段(A,B,C和D)。我使用按钮在它们之间导航,如果我从A到B,从B到A再次加载A,我不希望它发生。

这是我正在调用将片段加载到容器中的代码:

public void showNewFragment(Class<? extends Fragment> fragmentClass, Integer whereToPlaceId, Bundle bundle)
    {
        String tag = fragmentClass.getSimpleName();


        FragmentManager fm = getSupportFragmentManager();
        boolean inStack = fm.popBackStackImmediate(tag,0);



        FragmentTransaction fragTM = fm.beginTransaction();


        if(!inStack) {

            try {
                fragTM.add(whereToPlaceId, fragmentClass.newInstance(), tag);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        fragTM.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        fragTM.addToBackStack(tag);
        fragTM.commit();
    }

我也尝试使用onSaveInstanceState,但只在进行配置更改时调用它。

同样在保存此片段的活动中,我禁用了后退按钮导航。

编辑:

我在片段

中这样做了
    public static View rootView = null;

     @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


                if(rootView != null)
                    return rootView;
                //if not init rootView

                return rootView;
}

这是好方法吗?

0 个答案:

没有答案
相关问题