android - 如何在每次切换到 fragment 时不重新加载 Google map

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

我有一个基本布局,里面有一个 FragmentLayout。我还有一个抽屉导航,当单击抽屉的不同元素时,我会更改 FragmentLayout 的内容,如下所示:

FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new WhateverFragment());
fragmentTransaction.commit();

我正在使用的 fragment 之一中有一个 MapView。我在其 onCreateView 函数上初始化 mapView,如下所示:

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

        View v = inflater.inflate(R.layout.fragment_map, container, false);
        mapView = (MapView) v.findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);
        mapView.onResume();//needed to get the map to display immediately
        MapsInitializer.initialize(this.getActivity());
        mapView.getMapAsync(this);

        return v;
    }

但是每次我切换到这个 fragment 时都会调用这个函数,因此每次都会重置并重新加载 map (因此不会保留标记或任何内容)。

我应该把这个mapView初始化代码放在哪里,这样它就不会每次都被调用?

最佳答案

不要从 xml 初始化 MapView,而是考虑在代码中手动创建它,并在 fragment 中保留对其的 WeakReference

  1. 这样你就可以膨胀你的fragment的布局(没有MapView)
  2. 如果您的 MapView 字段为 null,请使用新的 MapView 对其进行初始化
  3. 然后将 MapView 字段作为子字段添加到膨胀的 xml 中。

关于android - 如何在每次切换到 fragment 时不重新加载 Google map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39316242/

相关文章:

android - 如何在Android中实现Google Directions API

java - 在 Android Studio 中找不到符号

android - 错误 : "package com.tumblr.remember does not exist." while building the app

java - 从 Activity 访问 ViewPager Fragment 方法

Android 谷歌地图自定义信息窗口

android - SupportMapFragment 不支持 AndroidX Fragment

android - 无法在带有android adt插件的eclipse中使用复选框

java - 从 RecyclerView 内的 onClickListener 启动 Activity 后出现 NullPointerException

java - 如何从android中的mainactivity中的url获取数据

android - 关于 inflater.inflate Android 文档的混淆