问题
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