2013-08-16 37 views
0

我正在開發一個應用程序使用谷歌地圖android api。該應用程序顯示用戶可以打開和關閉的各種tileoverlay。當我旋轉我的設備時,覆蓋層保持不變,但是當我單擊按鈕關閉我的覆蓋層時,我的設備就好像控制覆蓋層的變量爲空。在這種情況下,如何保持對tileoverlay的控制權。谷歌地圖方向變化後控制瓷磚疊加android api v2

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    SupportMapFragment mapFragment = 
      (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 

    //mMap=null; 
    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(); 
    setUpFieldsIfNeeded(); 
} 
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(); 

      } 
     } 
     } 
private void setUpFieldsIfNeeded(){    

    if (fieldsOverlay == null) { 
     TileProvider tileProvider = new UrlTileProvider(256, 256) { 
      @Override 
      public synchronized URL getTileUrl(int x, int y, int zoom) { 


       //String s = String.format(Locale.US, CMAFieldsRequestFormat, zoom, x, y); 
       String s = String.format(Locale.US, cartoDBFieldsTile, zoom, x, y); 
       s =s.replace(" ", "%20"); 
       System.out.println(s); 
       URL url = null; 
       try { 
        url = new URL(s); 
       } catch (MalformedURLException e) { 
        throw new AssertionError(e); 
       } 
       return url; 
      } 
     }; 


     fieldsOverlay = mMap.addTileOverlay(
       new TileOverlayOptions().tileProvider(tileProvider)); 
     fieldsOverlay.setVisible(false); 
     fieldsOverlay.setZIndex(1);} 

    } 

TLDR:我正在使用帶有名爲fieldsOverlay的tileOverlay的谷歌地圖。當我旋轉我的設備時,疊加層本身被保留,但它不再連接到變量fieldsOverlay。解決這個問題的最好方法是什麼?

感謝

編輯:我能得到應用出現的功能我想通過運行mMap.clear然後重新初始化我的層和可見性設置爲savedInstanceState值當我轉生我的活動的方式,但這似乎不是一個好的解決方案。

回答

1

使用SupportMapFragment.setRetainInstace看起來像是達到理想效果的一種快速方法,但實際上並非如此。

首先它會導致內存泄漏。看看我的gmaps-api-issue討論它。

您遇到的問題很正常。當重新創建Activity時,您保留的TileOverlay引用不會被保留。實際上創建了一個新的Activity對象。視覺對象應該像普通Android View一樣對待:配置更改時不保留。在the official documentation甚至有這方面的說明,但我現在找不到它。

如果您不使用setRetainInstance您不會因沒有引用您的對象而出現問題,因爲您必須在輪換時重新創建。

+0

您的解決方案非常完美。我從谷歌的地圖api示範項目中挑選了那行代碼,並且想警告其他人。 – user17601

+0

你可以發佈工作答案嗎? – superscral