My app displays a GoogleMap fragment successfully. But when clicking the "expand" button to load a new layout xml file, the map is now blank. I could load a new activity for the new layout, but this would duplicate quite a bit of code. Ideally, I would like to click the expand button and have the new layout load with the same map, but with reduced clutter on the screen.
I am unsure about how to handle the button click.
I initially tried setContentView(R.layout.activity_create_route_expanded); but then none of the buttons were clickable.
My current attempt inflates the new layout and then calls onCreate again
createRouteLayout = getLayoutInflater().inflate(R.layout.activity_create_route, null); Everything works except the blank map.
Here is a simplified version of my code:
public class CreateRouteActivity extends FragmentActivity implements OnMapReadyCallback {
private View createRouteLayout;
private ViewModelCreateRoute viewModelCreateRoute; // Save variable state when changing the layout
@Override
protected void onCreate(Bundle savedInstanceState) {
// If user has changed to/from expanded view, use the saved layout. Otherwise default to activity_create_route
if (createRouteLayout == null) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_route);
} else {
setContentView(createRouteLayout);
}
viewModelCreateRoute = new ViewModelProvider(this).get(ViewModelCreateRoute.class);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapCreateRoute);
mapFragment.getMapAsync(this); //See the callback below: onMapReady()
findViewById(R.id.createRouteExpandButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (viewModelCreateRoute.isExpanded()) {
viewModelCreateRoute.toggleExpanded();
createRouteLayout = getLayoutInflater().inflate(R.layout.activity_create_route, null);
} else {
viewModelCreateRoute.toggleExpanded();
createRouteLayout = getLayoutInflater().inflate(R.layout.activity_create_route_expanded, null);
}
onCreate(savedInstanceState);
}
});
}
@Override
public void onMapReady(GoogleMap gMap) {
viewModelCreateRoute.getMapDisplayContainer().setgMap(gMap);
MapUtils.populateMap(viewModelCreateRoute.getMapDisplayContainer(), true, false);
}
}
I still can't find a way to change the ContentView dynamically while displaying the map, but I did find an easier way to accomplish my goal:
Rather than building up a new layout, just change the ConstraintLayout dynamically:
In the Activity: