当旋转屏幕时回收Android Maps V2 SupportMapFragment

7
我希望提高SupportMapFragment在设备旋转时的性能。似乎必须重新创建该片段,但我并不确定。然而,当设备旋转时,地图瓦片必须重新加载。从性能的角度来看,保留整个mapfragment并重复使用它而无需重新实例化片段是有意义的。如果您对此有任何见解,我们将不胜感激。
我正在xml中声明SupportMapFragment,并使用api文档中描述的SetupMapIfNeeded()。
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();
        }
    }
}

你在这个问题上有什么进展了吗,帕特里克? - Aiden Fry
1个回答

11

看看样例中的RetainMapActivity类。非常好用。这是它:

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

}


但是您必须重新绘制标记!只需保留地图状态(缩放,位置等),而不是标记多边形... - Xenione
这个解决方案似乎有效。即使我使用了异步方法。但是在7次旋转后,地图会非常卡顿。 - user3528466

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接