【问题标题】:MapView inside custom RecyclerViewAdapter自定义 RecyclerViewAdapter 内的 MapView
【发布时间】:2019-01-25 23:18:51
【问题描述】:

我正在尝试实现一个包含 CardViews 的 RecyclerView,其中每个 MapView 都在里面。 问题是,在自定义适配器中初始化的 MapView 不会加载,除非您单击。 正如这里已经提到的:Android MapView does not load unless you touch on the 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 来解决这个问题。如果你这样做了,请告诉我。

【问题讨论】:

    标签: android android-recyclerview google-maps-android-api-2 android-mapview


    【解决方案1】:

    不要在回收器视图中使用地图视图,因为它是一个很重的组件,它会消耗更多内存,而是使用专为使用回收器视图/列表视图列出而设计的 lite 模式地图,有关更多详细信息,请参阅此链接 https://developers.google.com/maps/documentation/android-sdk/lite

    Google 也提供了如何使用 Lite 模式映射和回收器视图的演示,这里是 GitHub 的链接https://github.com/googlemaps/android-samples/blob/master/ApiDemos/java/app/src/main/java/com/example/mapdemo/LiteListDemoActivity.java

    【讨论】:

    • 谢谢你,就像一个魅力。您知道如何删除每个地图右下角的“导航到”和“在谷歌地图中打开”这些按钮吗?
    • 很高兴知道,我想设置地图 ui 属性 setMapToolbarEnabled(false) 会起作用,对于其他地图 ui 相关设置,您可以参考此链接developers.google.com/android/reference/com/google/android/gms/…
    • 最欢迎 :)
    【解决方案2】:

    一定要在 holder 中调用 onResume

    if (mapView != null) {
                    // Initialise the MapView
                    mapView.onCreate(null);
                    mapView.onResume();  //Probably U r missing this
                    // Set the map ready callback to receive the GoogleMap object
                    mapView.getMapAsync(this);
                }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 2021-12-31
    • 2019-01-12
    相关资源
    最近更新 更多