【问题标题】:Can't retain SupportMapFragment inside Fragment无法在 Fragment 中保留 SupportMapFragment
【发布时间】:2015-01-04 21:09:49
【问题描述】:

我有一个带有导航抽屉的应用程序,其中包含 Google 地图片段和其他一些片段。我正在以编程方式创建 SupportMapFragment 并将其放入地图容器中的自定义 fragment_map 布局中。

问题是我必须从数据库中向地图添加超过 2000 多个标记,但不想在每次设备旋转时都再次填充它们。我认为setRetainInstance(true) 会解决这个问题,但它不起作用 — 我得到了一张全新的地图,没有标记和相机在 0, 0 位置改变方向。示例应用程序在保留距离的情况下运行良好,但它们都在使用 FragmentActivity,这不是我的情况。这里的碎片有什么问题?

GoogleMapsFragment.java:

public class GoogleMapsFragment extends Fragment implements OnMapReadyCallback {

private SupportMapFragment mapFragment;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_map, container, false);

    FragmentManager fm = getChildFragmentManager();
    mapFragment = (SupportMapFragment) fm.findFragmentById(R.id.map_container);
    if (mapFragment == null) {
        mapFragment = SupportMapFragment.newInstance();
        mapFragment.getMapAsync(this);
        mapFragment.setRetainInstance(true);
        fm.beginTransaction().add(R.id.map_cont, mapFragment).commit();
    }
    return rootView;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    googleMap.addMarker(new MarkerOptions().position(new LatLng(5, 5)));

    // a long code with map initialization and adding markers here
    // ...
}
}

【问题讨论】:

标签: android google-maps android-fragments


【解决方案1】:

默认情况下,当配置发生变化时,例如方向,整个活动都会重新启动,但是您可以通过指定活动何时可以自行处理来阻止它这样做,这意味着您可以告诉活动不要重新启动,而是调用 onConfigurationChanged

在此处阅读更多信息: how can I save the fragment? when I rotate the screen

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 2015-04-25
    • 1970-01-01
    相关资源
    最近更新 更多