2014-03-24 69 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