Я использую методы show / hide, чтобы избежать создания нескольких MapView в MapActivity:
public class TabFragment extends SherlockFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getSherlockActivity().getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar
.newTab()
.setText("List")
.setTabListener(
new TabListener(((FragmentActivity) getActivity()), "listFragment", ListFragment.class)));
actionBar.addTab(actionBar
.newTab()
.setText("Map")
.setTabListener(
new TabListener(((FragmentActivity) getActivity()), "MapFragment", MapFragment.class)));
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_view, container, false);
}
public static class TabListener implements ActionBar.TabListener {
private final FragmentActivity activity;
private final String tag;
private final Class clazz;
private final Bundle args;
private Fragment fragment;
public TabListener(FragmentActivity activity, String tag, Class clz) {
this(activity, tag, clz, null);
}
public TabListener(FragmentActivity activity, String tag, Class clz, Bundle args) {
this.activity = activity;
this.tag = tag;
this.clazz = clz;
this.args = args;
// Check to see if we already have a fragment for this tab, probably from a previously saved state. If so,
// hide it, because our initial state is that a tab isn't shown.
fragment = activity.getSupportFragmentManager().findFragmentByTag(tag);
if (fragment != null && !fragment.isHidden()) {
FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
ft.hide(fragment);
ft.commit();
}
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (fragment == null) {
fragment = Fragment.instantiate(activity, clazz.getName(), args);
ft.add(R.id.container_fragment, fragment, tag);
} else {
ft.show(fragment);
}
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (fragment != null) {
ft.hide(fragment);
}
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
}