3 回答
TA贡献2041条经验 获得超4个赞
getMap现在不推荐使用
问题是当对getMap的调用为null时,何时可以重试?
这取决于问题的性质。
如果您在布局中设置SupportMapFragmentvia <fragment>元素,则可以getMap()在中成功调用onCreate()。但是,如果您SupportMapFragment通过构造函数创建via,那还为时过早- GoogleMap尚不存在。您可以扩展SupportMapFragment和覆盖onActivityCreated(),getMap()然后准备就绪。
但是,getMap()可以还回null了一个更大的问题,如没有安装谷歌播放服务。您可能需要使用类似的方法GooglePlayServicesUtil.isGooglePlayServicesAvailable()来检测这种情况并根据需要进行处理。
TA贡献1811条经验 获得超4个赞
我最终扩展了SupportMapFragment类并使用了回调。代码在这里:
public class MySupportMapFragment extends SupportMapFragment {
public MapViewCreatedListener itsMapViewCreatedListener;
// Callback for results
public abstract static class MapViewCreatedListener {
public abstract void onMapCreated();
}
@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
// Notify the view has been created
if( itsMapViewCreatedListener != null ) {
itsMapViewCreatedListener.onMapCreated();
}
return view;
}
}
我宁愿使用一个接口并覆盖onAttach(activity)方法,但就我而言,我不希望回调返回我的MainActivity。我希望它返回到Fragment的实例。(GoogleMap本质上是一个片段中的一个片段)我设置了回调并以此方式以编程方式加载了地图。我想在MySupportMapFragment的构造函数中设置itsMapViewCreatedListener,但是不建议使用无参数构造函数。
itsMySupportMapFragment = new MySupportMapFragment();
MapViewCreatedListener mapViewCreatedListener = new MapViewCreatedListener() {
@Override
public void onMapCreated() {
initPlacesGoogleMapCtrl();
}
};
itsMySupportMapFragment.itsMapViewCreatedListener = mapViewCreatedListener;
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.mapFragmentContainer, itsMySupportMapFragment);
transaction.addToBackStack(null);
transaction.commit();
然后,当我打回电话时,我可以得到地图。没有更多的空!
public void initPlacesGoogleMapCtrl() {
// Map ready, get it.
GoogleMap googleMap = itsMySupportMapFragment.getMap();
// Do what you want...
}
TA贡献1860条经验 获得超8个赞
我会评论CommonsWare的答案,但我对此没有足够的代表。无论如何,我也遇到了这样的问题,即getMap()在onActivityCreated中将返回null。我的设置是这样的:我有包含片段的MainActivity。在该片段的onCreateView方法中,我创建了SupportMapFragment,然后通过childFragmentManager将其添加到片段中。我一直引用SupportMapFragment,并希望它能在onActivityCreated中为我提供地图,但没有提供。该问题的解决方案是重写SupportMapFragment的onActivityCreated 而不是父片段。我是在onCreateView中这样做的:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_location, container, false);
mMapFragment = new SupportMapFragment() {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mMap = mMapFragment.getMap();
if (mMap != null) {
setupMap();
}
}
};
getChildFragmentManager().beginTransaction().add(R.id.framelayout_location_container, mMapFragment).commit();
return v;
}
- 3 回答
- 0 关注
- 1110 浏览
添加回答
举报