2013-02-11 69 views
7

我期望在设备旋转时提高SupportMapFragment的性能。好像该片段必须重新创建。我不确定这一点,但是当设备旋转时,必须重新加载地图块。从性能的角度来看,保留和重用整个映射片段而不必重新实例化片段是有意义的。任何深入了解这一点将不胜感激。回收Android地图V2支持地图片段旋转时

我在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(); 
     } 
    } 
} 
+0

你有这个Partick任何地方? – 2013-02-14 14:30:42

回答

10

查看示例中的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")); 
} 

}

+0

我错过了这个例子!谢谢 – Patrick 2013-02-17 14:51:55

+0

但你必须重新绘制标记!只是保持地图状态(缩放,位置等..),但不是标记polyno ... – Xenione 2014-07-25 07:38:39

+0

此解决方案似乎工作。即使我使用Asynk方法。但7轮后,地图滞后很多 – user3528466 2016-06-15 13:11:26