Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recycle Android Maps V2 SupportMapFragment when rotating

I am looking to improve the performance of the SupportMapFragment when the device is rotated. It seems as if the fragment must be recreated. I am not sure of this, however when the device is rotated the map tiles must be reloaded. It would make sense from a performance perspective to have the entire mapfragment retained and reused without having to re-instantiate the fragment. Any insight into this would be appreciated.

I am declaring the SupportMapFragment in xml and using the SetupMapIfNeeded() as described in the api docs.

private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the
    // map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map)).getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}
like image 762
Patrick Avatar asked Feb 11 '13 00:02

Patrick


1 Answers

Check out the RetainMapActivity class from the samples. Works like a charm. Here is is:

public class RetainMapActivity extends FragmentActivity {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.basic_demo);

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);

    if (savedInstanceState == null) {
        // First incarnation of this activity.
        mapFragment.setRetainInstance(true);
    } else {
        // Reincarnated activity. The obtained map is the same map instance in the previous
        // activity life cycle. There is no need to reinitialize it.
        mMap = mapFragment.getMap();
    }
    setUpMapIfNeeded();
}

@Override
protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
}

private void setUpMapIfNeeded() {
    if (mMap == null) {
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        if (mMap != null) {
            setUpMap();
        }
    }
}

private void setUpMap() {
    mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}

}

like image 113
alice_silver_man Avatar answered Nov 17 '22 07:11

alice_silver_man