【问题标题】:Best way to put a map (google maps v2) inside a fragment将地图(谷歌地图 v2)放在片段中的最佳方法
【发布时间】:2015-08-02 22:10:38
【问题描述】:

我有一个片段 (ApartmentFragment),它是一个显示公寓详细信息的页面。我想添加一张小地图来显示公寓的位置。 为了清楚起见,我使用的是 github 上的 MaterialNavigationDrawer,我的应用由单个 Activity(导航抽屉)和许多片段组成。

我读过的每一篇 stackoverflow 帖子都没有帮助到我。他们中的许多人都有些困惑。我不只想要 ApartmentFragment 内的地图,我想显示其他东西以及地图。 最好的方法是什么? 是否可以将 mapfragment 放入片段中?或者我需要在活动中转换 ApartmentFragment?

【问题讨论】:

  • 到目前为止你尝试过什么?发布您的代码。您可以拥有一个包含com.google.android.gms.maps.MapView 的布局,您可以从中获取对com.google.android.gms.maps.GoogleMap 的引用并对其进行操作。还可以查看 Airbnb 的 AirMapView github.com/airbnb/AirMapView
  • 我只是按照post 中的说明进行操作。在这个问题之前,我并没有真正意识到 MapView 的存在。感谢您向我推荐 AirMapView,它看起来是一个非常好的库,我会结帐 :)

标签: android android-fragments google-maps-android-api-2


【解决方案1】:

你读到的大部分内容都是正确的。您只需使用MapView 而不是MapFragment

https://developer.android.com/reference/com/google/android/gms/maps/MapView.html

然后在您的 ApartmenFragment 上,您必须对 mapview 进行所有回调

  • onCreate(Bundle)
  • onResume()
  • onPause()
  • onDestroy()
  • onSaveInstanceState()
  • onLowMemory()

像这样:

    private MapView mapView;

    @Nullable @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

       // inflate your view `root` and then call ...
       mapView = (MapView) root.indViewById(R.id.map_view);
       mapView.onCreate(savedInstanceState);
       mapView.getMapAsync(this);

       return root;
    }

    @Override public void onResume() {
       super.onResume();
       mapView.onResume();
    }

    @Override public void onPause() {
       super.onPause();
       mapView.onPause();
    }

    @Override public void onDestroyView() {
       super.onDestroyView();
       mapView.onDestroy();
    }

    @Override public void onSaveInstanceState(Bundle outState) {
       super.onSaveInstanceState(outState);
       mapView.onSaveInstanceState(outState);
    }

    @Override public void onLowMemory() {
       super.onLowMemory();
       mapView.onLowMemory();
    }

    @Override public void onMapReady (GoogleMap googleMap) {
          // from https://developer.android.com/reference/com/google/android/gms/maps/OnMapReadyCallback.html

          // and here you can do your map stuff with `googleMap`
    }

【讨论】:

  • 谢谢,我试试这个:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多