2016-03-22 22 views
3

我是一個在android studio編程的新手,我試圖在導航抽屜中使用Google Maps(設置目的地,路線和更多),其中我有多個片段,還有一個具體的對於谷歌地圖,我有麻煩使用標記和在onMapReady()方法在地圖上工作,我能夠發現,而不是我應該使用onActivityCreated()方法,但一旦我開始工作,它開始給我以下錯誤:不可轉換類型,不能投android.app.Fragmentcom.google.android.gms.maps.SupportMapFragment。在以下代碼行中:mapFragment = (SupportMapFragment) fm.findFragmentById(R.id.map);以及給我第二個錯誤:錯誤的第二個參數類型,找到:com.google.android.gms.maps.SupportMapFragment必需:android.app.Fragment在以下代碼行中:fm.beginTransaction().replace(R.id.map, mapFragment).commit();。不幸的是,我一直無法找到這個問題的答案或解決方案,並會感謝您的幫助。不可轉換類型;無法投射android.app.fragment

這裏是我在地圖位於片段的完整代碼:

package demo.mapas; 

import android.app.Fragment; 
import android.os.Bundle; 
import android.support.annotation.Nullable; 
//import android.support.v4.app.FragmentManager; 
import android.app.FragmentManager; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 

import com.example.usuario.mapas.R; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.OnMapReadyCallback; 
import com.google.android.gms.maps.SupportMapFragment; 

/** 
* Created by USUARIO on 3/12/2016. 
*/ 
public class opcion1Fragment extends Fragment { 
    private SupportMapFragment mapFragment; 




    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment_option1, container, false); 

     return rootView; 

    } 

    @Override 

    public void onActivityCreated(Bundle savedInstanceState){ 
     super.onActivityCreated(savedInstanceState); 

     FragmentManager fm = getChildFragmentManager(); 
     mapFragment = (SupportMapFragment) fm.findFragmentById(R.id.map); 
     if(mapFragment == null){ 
      mapFragment = SupportMapFragment.newInstance(); 
      fm.beginTransaction().replace(R.id.map, mapFragment).commit(); 
     } else { 
      mapFragment.getMapAsync(new OnMapReadyCallback() { 

       @Override 
       public void onMapReady(GoogleMap googleMap) { 
        googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); 

       } 
      }); 
     } 
    } 

} 

回答

7

opcion1Fragmentandroid.app.Fragment;延伸。但是你需要使用android.support.v4.app的課程。所以,你需要:

  1. 變化從進口:import android.app.Fragment;import android.support.v4.app.Fragment;
  2. import android.app.FragmentManager;的進口改爲import android.support.v4.app.FragmentManager;

而且你的問題將得到解決。

希望這有助於!

+0

解決了問題!深表讚賞! @ g2o –

+0

很高興幫助...請將問題標記爲已解決;) –

+0

好的答案:)它工作正常 – Mano

相關問題