【发布时间】:2022-01-13 00:41:07
【问题描述】:
我的应用成功显示了一个 GoogleMap 片段。 但是当单击“展开”按钮加载新的布局 xml 文件时,地图现在是空白的。 我可以为新布局加载一个新活动,但这会重复很多代码。 理想情况下,我想单击展开按钮并使用相同的地图加载新布局,但减少屏幕上的混乱。
我不确定如何处理按钮点击。
我最初尝试了setContentView(R.layout.activity_create_route_expanded);,但后来没有一个按钮是可点击的。
我目前的尝试膨胀新布局,然后再次调用 onCreate createRouteLayout = getLayoutInflater().inflate(R.layout.activity_create_route, null); 除了空白地图之外,一切正常。
这是我的代码的简化版本:
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);
}
}
【问题讨论】:
-
我仍然找不到在显示地图时动态更改 ContentView 的方法,但我确实找到了一种更简单的方法来实现我的目标:
标签: android google-maps layout setcontentview