Just to add to the existing answers here, I had been removing my Parcels from the saved state before calling mapView.onCreate
and it was working fine.
However after adding a ViewPager
to my Fragment I didn't realise that the BadParcelableException
had returned and the code made it to production. It turns out that the ViewPager
saves its state too and, because it's part of the Support Library, the Google Map cannot find the class to unparcel it.
So I opted to invert the process, instead of removing Parcels from the Bundle that I knew about, I opted to create a new Bundle for the map copying over only the map's state.
private final static String BUNDLE_KEY_MAP_STATE = "mapData";
@Override
public void onSaveInstanceState(Bundle outState) {
// Save the map state to it's own bundle
Bundle mapState = new Bundle();
mapView.onSaveInstanceState(mapState);
// Put the map bundle in the main outState
outState.putBundle(BUNDLE_KEY_MAP_STATE, mapState);
super.onSaveInstanceState(outState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map, container, false);
mapView = (MapView) view.findViewById(R.id.mapView);
mapView.getMapAsync(this);
Bundle mapState = null;
if (savedInstanceState != null) {
// Load the map state bundle from the main savedInstanceState
mapState = savedInstanceState.getBundle(BUNDLE_KEY_MAP_STATE);
}
mapView.onCreate(mapState);
return view;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…