Answer the question
In order to leave comments, you need to log in
How to reuse Google MapFragment?
There is MainActivity with NavigationDrawer. One of the fragments includes a map fragment (SupportMapFragment). When switching between them, I want the map not to be recreated. For this, we used this not the most beautiful, but working code with view reuse:
public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null) {
parent.removeView(view);
}
return view;
}
view = inflater.inflate(R.layout.fragment_map, container, false);
SupportMapFragment mapFragment = SupportMapFragment.newInstance();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.container, mapFragment).commit();
mapFragment.getMapAsync(new OnMapReadyCallback() {
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
setupMap();
}
});
return view;
}
Answer the question
In order to leave comments, you need to log in
You can use MapView instead of MapFragment.
private MapView mapView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_map, container, false);
boolean needSetupMap = true;
if (mapView != null) {
ViewGroup parentViewGroup = (ViewGroup) mapView.getParent();
if (parentViewGroup != null) {
parentViewGroup.removeView(mapView);
needSetupMap = false;
}
} else {
mapView = new MapView(getActivity());
mapView.onCreate(Bundle.EMPTY);
}
((ViewGroup)view.findViewById(R.id.container)).addView(mapView);
if (needSetupMap) {
mapView.getExtendedMapAsync(new OnMapReadyCallback() {
public void onMapReady(GoogleMap googleMap) {
setUpMap(GoogleMap);
}
});
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question