Skip to content

Instantly share code, notes, and snippets.

@mcassiano
Last active July 20, 2018 11:00
Show Gist options
  • Save mcassiano/2fdd187e476a6e07a1816ad841908146 to your computer and use it in GitHub Desktop.
Save mcassiano/2fdd187e476a6e07a1816ad841908146 to your computer and use it in GitHub Desktop.
public class ExampleActivity extends AppCompatActivity implements OnMapReadyCallback {
private MapViewObserver mapView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_estimate);
MapView view = findViewById(R.id.map_view);
mapView = new MapViewObserver(getLifecycle(), view, this);
mapView.onCreate(savedInstanceState);
}
@Override
public void onMapReady(GoogleMap googleMap) {
// do whatever
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstance(outState);
}
}
public class MapViewObserver implements LifecycleObserver {
private static final String MAPVIEW_BUNDLE_KEY = "MapViewBundleKey";
private final MapView mapView;
private final Lifecycle lifecycle;
private final OnMapReadyCallback callback;
public MapViewObserver(@NonNull Lifecycle lifecycle,
@NonNull MapView mapView,
@NonNull OnMapReadyCallback callback) {
this.lifecycle = Preconditions.checkNotNull(lifecycle);
this.mapView = Preconditions.checkNotNull(mapView);
this.callback = Preconditions.checkNotNull(callback);
lifecycle.addObserver(this);
}
public void onCreate(Bundle bundle) {
Bundle mapViewBundle = null;
if (bundle != null) {
mapViewBundle = bundle.getBundle(MAPVIEW_BUNDLE_KEY);
}
mapView.onCreate(mapViewBundle);
mapView.getMapAsync(callback);
}
public void onSaveInstance(Bundle bundle) {
Bundle mapViewBundle = bundle.getBundle(MAPVIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
bundle.putBundle(MAPVIEW_BUNDLE_KEY, mapViewBundle);
}
mapView.onSaveInstanceState(mapViewBundle);
}
@OnLifecycleEvent(value = Lifecycle.Event.ON_RESUME)
void onResume() {
mapView.onResume();
}
@OnLifecycleEvent(value = Lifecycle.Event.ON_START)
void onStart() {
mapView.onStart();
}
@OnLifecycleEvent(value = Lifecycle.Event.ON_STOP)
void onStop() {
mapView.onStop();
}
@OnLifecycleEvent(value = Lifecycle.Event.ON_PAUSE)
void onPause() {
mapView.onPause();
}
@OnLifecycleEvent(value = Lifecycle.Event.ON_DESTROY)
void onDestroy() {
mapView.onDestroy();
lifecycle.removeObserver(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment