使用谷歌地图支持片段

时间:2016-03-28 09:21:34

标签: android google-maps android-fragments

我在我的应用程序中使用谷歌地图片段并面临一个问题。

我收到此错误

  

" java.lang.IllegalStateException:失败保存状态:活动   SupportMapFragment {212f6b1}已清除索引:-1"

当我的手机进入睡眠状态时,包含谷歌地图的片段处于活动状态。 我的代码包含谷歌地图:

public class MapFragment extends Fragment implements OnMapReadyCallback{

public MapFragment() {
}

GoogleMap mgoogleMap;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    Log.d("cycle","Mapfragment-created");
    View RootView = inflater.inflate(R.layout.mapfragment, container, false);
    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    return RootView;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    Log.d("map", "OnMapReady");
    if (mgoogleMap == null)
        mgoogleMap = googleMap;
}

@Override
public void onResume() {
    super.onResume();
    Log.d("cycle-mapfragment","onResume");
}

@Override
public void onPause() {
    super.onPause();
    Log.d("cycle-mapfragment", "onPause");
}

@Override
public void onStop() {
    super.onStop();
}

@Override
public void onDestroyView() {
    try {
        SupportMapFragment fragment = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map));
        FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
        ft.remove(fragment);
        ft.commit();
    } catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        super.onDestroyView();
    }
}
}

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我修好了删除这一行

fm.executePendingTransactions();

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mMapView = new SupportMapFragment();
    FragmentManager fm = getChildFragmentManager();
    fm.beginTransaction().replace(R.id.map, mMapView).commit();
    //fm.executePendingTransactions();
}