Android创建片段不止一次

时间:2012-04-11 11:49:33

标签: android android-fragments fragment

使用此sample:我创建了自己的Fragment,其中包含tabhost和tab内容:

    public class TabsFragment extends Fragment
    {
        private static final String EXTRA_TAB = "EXTRA_TAB";

        private TabHost tabHost;
        private TabManager tabManager;
        private MaptrixFragmentActivity activity;
        private Context context;

        @Override
        public void onAttach(Activity activity) 
        {
            this.activity = (MaptrixFragmentActivity) activity;
            this.context = activity;
            super.onAttach(activity);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
        {
            View view = inflater.inflate(R.layout.fragment_tabs, container, false);
            tabHost = (TabHost)view.findViewById(android.R.id.tabhost);
            tabHost.setup();
            tabManager = new TabManager(activity, tabHost, R.id.realtabcontent);

            initTabs();

            if (savedInstanceState != null)
            {
                tabHost.setCurrentTabByTag(savedInstanceState.getString(EXTRA_TAB));
            }
            return view;
        }

        private void initTabs()
        {   
            // tab one
            addTab(Fragment.class, null, R.drawable.icon1, Res.S(R.string.tab1));

            // I have not implement the tab fragment yet!

            // tab two
            addTab(Fragment.class, null, R.drawable.icon2, Res.S(R.string.tab2));
        }

        private void addTab(Class<?> fragmenClass, Bundle bundle, int drawableId, String tag)
        {
            TabHost.TabSpec spec = tabHost.newTabSpec(tag);
            View tabIndicator = LayoutInflater.from(context).inflate(R.layout.item_tab, tabHost.getTabWidget(), false);
            ImageView icon = (ImageView) tabIndicator.findViewById(R.id.tab_image);
            icon.setImageResource(drawableId);
            spec.setIndicator(tabIndicator);
            tabManager.addTab(spec, fragmenClass, bundle);
        }

        @Override
        public void onSaveInstanceState(Bundle outState) 
        {
            super.onSaveInstanceState(outState);
            outState.putString(EXTRA_TAB, tabHost.getCurrentTabTag());
        }

        public static class TabManager implements TabHost.OnTabChangeListener 
        {
            private final FragmentActivity activity;
            private final TabHost tabHost;
            private final int containerID;
            private final HashMap<String, TabInfo> tabs = new HashMap<String, TabInfo>();
            TabInfo lastTab;
            TabFactory factory;

            public TabManager(FragmentActivity activity, TabHost tabHost, int containerID) 
            {
                this.activity = activity;
                this.tabHost = tabHost;
                this.containerID = containerID;
                factory = new TabFactory(activity);
                tabHost.setOnTabChangedListener(this);
            }

            public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) 
            {
                tabSpec.setContent(factory);
                String tag = tabSpec.getTag();

                TabInfo info = new TabInfo(tag, clss, args);

                info.fragment = activity.getSupportFragmentManager().findFragmentByTag(tag);

                if (info.fragment != null && !info.fragment.isDetached()) 
                {
                    FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
                    ft.detach(info.fragment);
                    ft.commit();
                }

                tabs.put(tag, info);
                tabHost.addTab(tabSpec);
            }

            @Override
            public void onTabChanged(String tabId) 
            {
                TabInfo newTab = tabs.get(tabId);
                if (lastTab != newTab) 
                {
                    FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
                    if (lastTab != null) {
                        if (lastTab.fragment != null) 
                        {
                            ft.detach(lastTab.fragment);
                        }
                    }
                    if (newTab != null) 
                    {
                        if (newTab.fragment == null) 
                        {
                            newTab.fragment = Fragment.instantiate(activity, newTab.clss.getName(), newTab.args);
                            ft.add(containerID, newTab.fragment, newTab.tag);
                        } 
                        else 
                        {
                            ft.attach(newTab.fragment);
                        }
                    }

                    lastTab = newTab;
                    ft.commit();
                }
            }
        }

        private static class TabInfo 
        {
            private final String tag;
            private final Class<?> clss;
            private final Bundle args;
            private Fragment fragment;

            TabInfo(String _tag, Class<?> _class, Bundle _args) 
            {
                tag = _tag;
                clss = _class;
                args = _args;
            }
        }

        private static class TabFactory implements TabHost.TabContentFactory 
        {
            private final Context mContext;

            public TabFactory(Context context) 
            {
                mContext = context;
            }

            @Override
            public View createTabContent(String tag) 
            {
                View v = new View(mContext);
                v.setMinimumWidth(0);
                v.setMinimumHeight(0);
                return v;
            }
        }
    }

但是当设备更改方向时,onCreateView方法会调用两次或更多次。

My FragmentActivity是:

    public class MaptrixFragmentActivity extends FragmentActivity
    {
        @Override
        protected void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.factivity);

            replace(R.id.factivity_content, new TabsFragment(), false, false);
        }

        @Override
        protected void onResume()
        {
            super.onResume();
        }

        @Override
        protected void onPause()
        {
            super.onPause();
        }

        public void replace(int rootView, Fragment fragment)
        {
            replace(rootView, fragment, true,  true);
        }

        public void replace(int rootView, Fragment fragment, boolean backStack)
        {
            replace(rootView, fragment, backStack,  true);
        }

        public void replace(int rootView, Fragment fragment, boolean backStack,  boolean animation)
        {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (animation) transaction.setCustomAnimations(R.anim.fragment_open, R.anim.fragment_close, R.anim.fragment_open_stack, R.anim.fragment_close_stack);
            if (backStack) transaction.addToBackStack(null);
            transaction.replace(R.id.factivity_maptrix_content, fragment);
            transaction.commit();
        }
    }

为什么我有这个错误?

1 个答案:

答案 0 :(得分:1)

您可以将android:configChanges="keyboardHidden|orientation"添加到AndroidManifest.xml文件中。这样可以避免在方向更改时重新创建活动,因此TabsFragment将不会创建两次。

<activity android:name="MaptrixFragmentActivity" android:configChanges="keyboardHidden|orientation">

有关详细信息,请参阅this