2017-04-17 47 views
0

我是新來的android編程,一直在努力解決這個問題。我讀了getMap()已被棄用,取而代之的是getMapAsync() 但是,我似乎無法找到使用getMayAsync()的方式,因爲它使用片段資源,直到現在我並不需要片段資源。無法解析getMap()或替換爲getMapAsync()

這裏是我的代碼:

public class RunMapFragment extends SupportMapFragment { 
    private static final String ARG_RUN_ID = "RUN_ID"; 
    private GoogleMap mGoogleMap; 
    public static RunMapFragment newInstance(long runId) { 
     Bundle args = new Bundle(); 
     args.putLong(ARG_RUN_ID, runId); 
     RunMapFragment rf = new RunMapFragment(); 
     rf.setArguments(args); 
     return rf; 
    } 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, 
          Bundle savedInstanceState) { 
     View v = super.onCreateView(inflater, parent, savedInstanceState); 
     mGoogleMap = getMap(); //Error here 
     mGoogleMap.setMyLocationEnabled(true); 
     return v; 
    } 
} 

任何幫助將非常感激。 是否可以將地圖API最小sdk回滾到可以使用getMap()的版本9?

回答

1

getMap()方法was deprecated and then removed,所以你需要使用getMapAsync()來代替。

當片段直接擴展SupportMapFragment時,不需要覆蓋onCreateView()

相反,只需調用getMapAsync()onResume()覆蓋,並使用在onMapReady()覆蓋返回谷歌地圖參考:

public class RunMapFragment extends SupportMapFragment { 
    private static final String ARG_RUN_ID = "RUN_ID"; 
    private GoogleMap mGoogleMap; 
    public static RunMapFragment newInstance(long runId) { 
     Bundle args = new Bundle(); 
     args.putLong(ARG_RUN_ID, runId); 
     RunMapFragment rf = new RunMapFragment(); 
     rf.setArguments(args); 
     return rf; 
    } 

    @Override 
    public void onResume() { 
     super.onResume(); 
     if (mGoogleMap == null) { 
      getMapAsync(this); 
     } 
    } 

    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mGoogleMap = googleMap; 
     mGoogleMap.setMyLocationEnabled(true); 
    } 
} 

請注意,如果你的目標API-23或更高,你會在使用setMyLocationEnabled()方法之前,需要確保用戶在運行時批准了位置許可權,更多信息請參閱my answer here

+0

非常感謝你! –