我有一个非常复杂的应用程序,具有各种不同的功能。其中一个功能包括谷歌地图选项卡。应用程序的结构使得每个选项卡都是一个片段。 在这种特殊情况下,我无法声明我的谷歌地图对象获取当前位置数据。
public static class GpsClass extends Fragment{
View rootView;
private GoogleMap mMap;
public static final String ARG_SECTION_NUMBER = "section_number";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
if (rootView != null){
((ViewGroup) rootView.getParent()).removeView(rootView);
}
try{
rootView = inflater.inflate(R.layout.gps, container,false);
mMap = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.mymap)).getMap();
mMap.setMyLocationEnabled(true);
} catch(InflateException e){
}
return rootView;
}
}
在我的代码实现中,当我尝试声明mMap时,我得到一个空指针异常。如果我删除 getAvtivity()调用,eclipse告诉我我不能对非静态方法进行静态引用。如果我删除了mMap行,我的应用程序在一个选项卡中使用谷歌地图(其他选项卡实现其他所有工作)。
答案 0 :(得分:2)
你能包含你的布局xml吗?
如果地图片段为SupportMapFragment
(com.google.android.gms.maps.SupportMapFragment
),请使用:
mMap = ((SupportMapFragment) getFragmentManager ().findFragmentById (R.id.map)).getMap ();
或
如果地图片段为MapFragment
(com.google.android.gms.maps.MapFragment
),请使用:
mMap = ((MapFragment) getFragmentManager ().findFragmentById (R.id.map)).getMap ();
编辑: OP问题的实际答案: 在布局XML中声明它时,请确保使用Map Fragment的正确类名。
答案 1 :(得分:0)
试试这个
GoogleMap mMap = ((SupportMapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
和你的xml
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />