【发布时间】:2015-01-29 19:58:20
【问题描述】:
我在布局中使用 GoogleMap/MapView,但作为 View 而不是 Fragment(因为父级需要是 Fragment),所以 Fragment 的布局包括:
<com.google.android.gms.maps.MapView
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
片段包含以下内容:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
<......>
initMap(bundle, mapView);
return rootView;
}
@Override
public void onResume() {
super.onResume();
MyApp.bus.register(this);
updateMapLocation(MyApp.getMostRecentLocation());
}
@Override
public void onPause() {
super.onPause();
MyApp.bus.unregister(this);
}
@Subscribe
public void locationReceived(LocationReceived m) {
Timber.i("Received bus message - Location!");
updateMapLocation(MyApp.getMostRecentLocation());
}
它的父片段包含这个:
private MapView mapView;
private GoogleMap map;
@Override
public void onResume() {
super.onResume();
if (mapView!=null) {
mapView.onResume();
map = this.mapView.getMap();
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (mapView!=null) mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (mapView!=null) mapView.onLowMemory();
}
protected void initMap(Bundle bundle, MapView mapView) {
this.mapView = mapView;
this.mapView.onCreate(bundle);
map = this.mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
map.setBuildingsEnabled(true);
map.getUiSettings().setZoomControlsEnabled(false);
map.getUiSettings().setMyLocationButtonEnabled(true);
try {
MapsInitializer.initialize(this.getActivity());
} catch (Exception e) {
Timber.e(e, "Error initialising Google Map");
}
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(MyApp.getCentralUKLatLng(), getResources().getInteger(R.integer.map_zoom_initial));
map.animateCamera(cameraUpdate);
}
@Override
public void onPause() {
super.onPause();
if (mapView!=null) mapView.onPause();
}
protected void updateMapLocation(Location location) {
Timber.i("Moving map to a new location: " + location);
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15);
map.animateCamera(cameraUpdate);
}
正在通过 Otto 巴士运送新地点。上面的代码完美运行,但只是第一次。如果我在此之前打开另一个片段,然后再次关闭它,则地图无法动画到随后提供的位置。肯定会收到位置,肯定会调用 animateCamera() 方法(使用有效的位置和缩放),但绝对没有任何反应。没有错误,没有日志消息,什么都没有。更令人恼火的是在一个 Fragment(与上面的代码相同)上,它在恢复 Fragment 时工作正常。
我认为我在恢复时(重新)初始化 GoogeMap 或 MapView 的方式有问题,但我正在通过 onPause() 和 onResume() 调用 MapView,我理解这是必要的。我还需要做什么?
【问题讨论】:
-
我认为你对代码的改动太多了......片段调用 initMap 但它是在你所谓的“父”片段中定义的。有两个碎片吗?当您在第二张地图关闭时尝试注册/取消注册时,有些东西会丢失。
-
"...作为视图而不是片段(因为父级需要是片段)"为什么不使用嵌套片段?
-
@peguerosdc 我认为您不能将 MapFragment 放在 XML 布局文件中并将其膨胀到片段中。如果你想在另一个 Fragment 中使用 MapFragment,你必须以编程方式创建它。
-
您应该使用
MapView.getMapAsync而不是MapView.getMap并对updateMapLocation中的地图进行空检查。不过,这可能无法解决您的问题。 -
也许你可以尝试在你的 GoogleMap.animate 方法中添加一个回调,看看动画是完成还是取消。
标签: android google-maps-android-api-2 android-mapview