Avoid reloading data in FragmentTabHost tab switching

此生再无相见时 提交于 2020-01-04 19:12:22

问题


I have Tabbed layout with two fragments using FragmentTabHost. On tab selection each fragment is re-created (onCreateView, onActivityCreated... called again). I loads data in first fragment (in onCreateView) move to other tab and when I come back to first fragment, whole fragment is recreated and so data is again loaded. I don't want to load data again and again on tab switching. What should I do?

I tried attaching and detaching fragments instead of adding/replacing but all Fragment life cycle methods are still being called again and again on tab switching. What is the right way to achieve desired behavior?


回答1:


You should hide and show your fragments. Otherwise onCreateView gets called if you add/replace. So if the fragment is already present, use show and hide.

In your onTabChanged, please add the below code.

if (mLastTab != newTab) {
            FragmentTransaction ft = this.getSupportFragmentManager()
                    .beginTransaction();
            if (mLastTab != null) {
                if (mLastTab.fragment != null) {
                    ft.hide(mLastTab.fragment);
                }
            }
            if (newTab != null) {
                if (newTab.fragment == null) {
                    newTab.fragment = Fragment.instantiate(this,
                            newTab.clss.getName(), newTab.args);
                    ft.add(android.R.id.tabcontent, newTab.fragment, newTab.tag);
                } else {
                    ft.show(newTab.fragment);
                }
            }


来源:https://stackoverflow.com/questions/25423873/avoid-reloading-data-in-fragmenttabhost-tab-switching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!