我正在尝试实现一个包含 CardView 的 RecyclerView,其中包含每个 MapView。
问题是,在自定义适配器中初始化的 MapView 不会加载,除非您单击它。
正如这里已经提到的:Android MapView 不会加载,除非你触摸地图视图
您可以通过重写 onResume() 来解决该问题。
我已经尝试过以下方式:
@Override
public void onResume() {
if(LocationsAdapter.ViewHolder.mapView != null) {
LocationsAdapter.ViewHolder.mapView.onResume();
}
super.onResume();
}
老实说,我根本不知道如何以任何其他方式覆盖 onResume,如果我在这里违反了某些编程规则,请原谅我。 我在 LocationsAdapter 中创建的 ViewHolder 中将 mapView 设置为公共静态。这似乎不起作用,地图仍然是空白。
Adapter内部的ViewHolder实现了OnMapReadyCallback。
public static class ViewHolder extends RecyclerView.ViewHolder implements OnMapReadyCallback
...
@Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
Location location = locations.get(getAdapterPosition());
this.googleMap.addMarker(new MarkerOptions().position(location.getLatlng()).title(location.getName()));
this.googleMap.moveCamera(CameraUpdateFactory.newLatLng(location.getLatlng()));
this.googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(location.getLatlng(), 7.0f));
}
这两个方法是在调用ViewHolder时调用的。
mapView.onCreate(null);
mapView.getMapAsync(this);
另一篇提到此问题的文章尚未得到解答:mapView inside cardview not load the map
。 我的目标是,无论片段当前处于什么生命周期,都加载地图。 我假设您既不需要适配器、片段也不需要 XML 来解决这个问题。如果您这样做,请告诉我。