Recycle Android Maps V2 SupportMapFragment when rotating

泄露秘密 提交于 2019-11-29 03:28:47

问题


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

回答1:


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

}



来源:https://stackoverflow.com/questions/14804137/recycle-android-maps-v2-supportmapfragment-when-rotating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!