2013-02-11 66 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