P
P
pengrad2015-02-23 23:27:59
Android
pengrad, 2015-02-23 23:27:59

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;
}

In the latest version of Play Services (6.5.87) and Support Library (21.0.3), this feature is no longer available. When you reopen the fragment, the map is not displayed. All other elements are displayed and the map is blank.
I can normally do "inflate view" all the time, but there are thousands of markers on the map (clustered via maps-extensions) and redrawing them takes a noticeable amount of time.
Is there any way to not recreate the map?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
pengrad, 2015-03-16
@pengrad

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 question

Ask a Question

731 491 924 answers to any question