2014-03-24 78 views
0

我想顯示谷歌地圖,我還沒有使用片段太多,所以我懷疑是我的問題是..顯示谷歌地圖片段/活性

我對LocatorMap.java Java類:

public class LocatorMap extends Fragment { 

    MapView m; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     // inflat and return the layout 
     View v = inflater.inflate(R.layout.activity_locator_map, container, false); 
     m = (MapView) v.findViewById(R.id.mapView); 
     m.onCreate(savedInstanceState); 

     return v; 
    } 

    @Override 
    public void onResume() { 
     super.onResume(); 
     m.onResume(); 
    } 

    @Override 
    public void onPause() { 
     super.onPause(); 
     m.onPause(); 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     m.onDestroy(); 
    } 

    @Override 
    public void onLowMemory() { 
     super.onLowMemory(); 
     m.onLowMemory(); 
    } 

和我的活動XML是:

<?xml version="1.0" encoding="utf-8"?> 
<com.google.android.gms.maps.MapView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/mapView" /> 

,我試圖提出這樣的觀點:

Intent intent = new Intent(getApplicationContext(), LocatorMap.class); 
    startActivity(intent); 

當我這樣做,我得到:

Unable to instantiate activity ComponentInfo{my package name.LocatorMap} 

cannot cast to android.app.Activity

我在做什麼錯?

回答

1
public class LocatorMap extends Fragment { 

它不是一個Activity類,你不能使用

Intent intent = new Intent(getApplicationContext(), LocatorMap.class); 
startActivity(intent); 

你需要的是在活動佈局向其中添加片段的容器。

更多信息

http://developer.android.com/guide/components/fragments.html

一般容器是FrameLayout。在活動xml中添加一個FrameLayout與id fragment_container,並在Activity類中具有以下代碼。

LocatorMap newFragment = new LocatorMap() ; 
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 
transaction.replace(R.id.fragment_container, newFragment); 
transaction.addToBackStack(null); // if you want fragment to be added to backstack 
transaction.commit(); 
+0

我把這段代碼放在我的活動班的onCreate方法中嗎? – BluGeni

+0

@BluGeni是的,你可以 – Raghunandan