2011-08-17 93 views
0

我試圖將我的地圖視圖從標準地圖視圖切換到衛星。本網站上有人向我提供了以下代碼。但是'mMapView'在紅色中被強調爲錯誤,並且執行建議的解決方案不起作用。Android地圖視圖切換

請向我解釋我做錯了什麼,我能做些什麼來解決這個問題。謝謝。

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
switch (item.getItemId()) { 
case R.id.mapview : 
if(mMapView.isSatellite()) { 
mMapView.setSatellite(false); 
} else { 
mMapView.setSatellite(true); 
} 
default : 
return super.onOptionsItemSelected(item); 
} 
} 

我的onCreate是:

public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.map); 
MapView mapView = (MapView) findViewById(R.id.mapview); 
mapView.setBuiltInZoomControls(true); 
mapView.setSatellite(false); 
} 

回答

2

用的MapView創建一個域,並在 「OnOptionItemSelected」 使用它。這樣的事情:

private MapView mapView; 
... 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.map); 
    mapView = (MapView) findViewById(R.id.mapview); 
    mapView.setBuiltInZoomControls(true); 
    mapView.setSatellite(false); 
} 
... 
@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
//this should be the id for the item in the menu, no for the map. 
//if you select the item in the menu that toggle the view of your map, then, change the map 
//I copied your code, but becareful because I think this can give you problems (about 
//having the same ids for the map and for the item in the same spacename ("id") 
       case R.id.mapview : 
       if(mapView.isSatellite()) { 
        mapView.setSatellite(false); 
       } else { 
        mapView.setSatellite(true); 
       } 
       default : 
       return super.onOptionsItemSelected(item); 
       } 
      } 
+0

應該做的伎倆。我自己沒有在我的項目中使用'onOptionItemSelected()',但是我沒有看到這段代碼有任何問題 –

0

@Finuka - 這不會幫助解決問題。這反而使他們有錯誤:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.map); 
    mapView = (MapView) findViewById(R.id.mapview); 
    mapView.setBuiltInZoomControls(true); 
    mapView.setSatellite(false); 
} 

應該是這樣,這是他們最初使用:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.map); 
    MapView mapView = (MapView) findViewById(R.id.mapview); 
    mapView.setBuiltInZoomControls(true); 
    mapView.setSatellite(false); 
} 

我在地圖應用程序中嘗試這樣做。 (我沒有添加切換功能,因爲我不需要一個)

+0

在我的地圖應用程序中,我使用切換功能和我發佈的代碼,爲我工作。從我的觀點來看,在代碼中有兩個問題:一個是mMapView沒有鏈接到真實地圖視圖。其次,mapview和菜單中項目的ID是相同的。 – Finuka

+0

@Finuka - 錯過了你的'私人MapView mapView';'當我做到這一點的時候會出來。這適用於我的地圖應用程序,所以我可以確認最初的解決方案。 (我只是顯然不懂如何!) – oli

+0

好吧,如果你不需要在膨脹之後修改地圖,那爲什麼它適合你。但是,如果你想添加切換功能,地圖應該可以從班級的每個部分訪問。所以我把它當作一個領域。 – Finuka