首页 > 解决方案 > 哪种方法可以防止谷歌地图重新创建?

问题描述

在我的项目中,我有底部导航。

fragmentManager.beginTransaction().add(R.id.container, profile, "profile").detach(profile).commit();
fragmentManager.beginTransaction().add(R.id.container, news, "news").detach(news).commit();
fragmentManager.beginTransaction().add(R.id.container, map, "map").commit();
currentFragment = map;

我使用分离/附加在片段之间导航。

fragmentManager.beginTransaction().detach(currentFragment).commit();
fragmentManager.beginTransaction().attach(newFragment).commit();
currentFragment = newFragment; 

每次我用地图附加片段时,谷歌地图都会重新创建,并且 onMapReady 会调用。因此,地图不会保留其属性。在片段之间导航或保存地图属性的正确方法是什么?

UPD:地图片段

private static final String TAG = "MapFragment";
private static final int ERROR_DIALOG_REQUEST = 9001;
private static final float MOSCOW_ZOOM = 9.8f;
private static final LatLng MOSCOW_LATLNG = new LatLng(55.751498, 37.618767);

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

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    if (isServicesOK()) {
        initMap();
    }
}

private void initMap() {
    SupportMapFragment mMapFragment = (SupportMapFragment) this.getChildFragmentManager()
            .findFragmentById(R.id.map);

    assert mMapFragment != null;
    mMapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    googleMap.setMinZoomPreference(8f);
    LatLngBounds MOSCOW = new LatLngBounds(
            new LatLng(55.40217, 37.23093), new LatLng(56.10699, 37.95694));

    googleMap.setLatLngBoundsForCameraTarget(MOSCOW);
    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(MOSCOW_LATLNG, MOSCOW_ZOOM));
}

public boolean isServicesOK(){
    int available = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(getContext());

    if(available == ConnectionResult.SUCCESS){
        return true;
    }
    else if(GoogleApiAvailability.getInstance().isUserResolvableError(available)){
        Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(getActivity(), available, ERROR_DIALOG_REQUEST);
        dialog.show();
    }else{
        Toast.makeText(getContext(), "You can't make map requests", Toast.LENGTH_SHORT).show();
    }
    return false;
}

标签: javaandroidgoogle-mapsandroid-fragments

解决方案


推荐阅读