I am using the new snapshot () method of the GoogleMap
object, and in SnapshotReadyCallback I am replacing the MapView
in my layout for ImageView
with the Bitmap
passed to me from the callback. Unfortunately, about this, despite the fact that I get Bitmap
, it seems that the snapshot was taken before the map was rendered.
I should also add that this view is created programmatically and is not added to the action right away (it actually fits in the ScrollView with a bunch of other views).
The essence of my code (for brevity):
public class MyCustomView extends LinearLayout { private FrameLayout mapContainer; @Override public void onAttachedToWindow() { super.onAttachedToWindow(); // Setup GoogleMapOptions ... mapView = new MapView(getContext(), googleMapOptions); mapContainer.addView(mapView); mapView.onCreate(null); mapView.onResume(); // Setup CameraUpdate ... mapView.getViewTreeObserver().addOnGlobalLayoutListener(new MapLayoutListener(mapView, cameraUpdate)); } private class MapLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener { private final WeakReference<MapView> mapViewReference; private final CameraUpdate cameraUpdate; public MapLayoutListener(MapView mapView, CameraUpdate cameraUpdate) { mapViewReference = new WeakReference<MapView>(mapView); this.cameraUpdate = cameraUpdate } @Override public void onGlobalLayout() { MapView mapView = mapViewReference.get(); if (mapView == null) { return; } mapView.getViewTreeObserver().removeOnGlobalLayoutListener(this); GoogleMap map = mapView.getMap(); if (map == null) { return; } try { map.moveCamera(cameraUpdate); } catch (IllegalStateException e) { e.printStackTrace(); } map.snapshot(new GoogleMap.SnapshotReadyCallback() { @Override public void onSnapshotReady(Bitmap bitmap) { MapView mapView = mapViewReference.get(); if (mapView == null) { return; } mapContainer.removeAllViews(); ImageView imageView = new ImageView(getContext()); imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); imageView.setImageBitmap(bitmap); mapContainer.addView(imageView); } }); } } }
Sometimes an IllegalStateException
occurs when calling map.moveCamera(cameraUpdate)
, complaining that the view has not yet been laid out, but I call it inside the OnGlobalLayoutListener
, which I thought was the right way to get a callback when your view is done by rendering / styling, etc. d. This exception makes me think differently.
So what is the right way to do this? Documents are scarce in detail, and the "life cycle" of the "View" is not very clear. I need a callback when View is ready for me to call snapshot()
source share