对我来说,解决方案是将所有必要的生命周期方法从包含 MapView 的 Fragment 转发到 MapView 中的相应方法。就我而言,在 onCreate()创建 MapView 后,我在onCreateView()的片段布局内将 MapView 动态添加到 FrameLayout 中。
public class MapFragment extends Fragment {
private MapView mapView;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mapView = new MapView(requireContext()); // obtain the mapView before calling .onCreate() on it.
mapView.onCreate(savedInstanceState);
}
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_map, null, false);
mapContainer = (FrameLayout) rootView.findViewById(R.id.map_container);
mapContainer.removeAllViews();
mapContainer.addView(mapView);
return rootView;
}
@Override
public void onStart() {
super.onStart();
if (mapView != null) {
mapView.onStart();
}
}
@Override
public void onResume() {
super.onResume();
if (mapView != null) {
mapView.onResume();
}
}
@Override
public void onPause() {
super.onPause();
if (mapView != null) {
mapView.onPause();
}
}
@Override
public void onStop() {
super.onStop();
if (mapView != null) {
mapView.onStop();
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (mapView != null) {
mapView.onDestroy();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mapView != null) {
mapView.onSaveInstanceState(outState);
}
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (mapView != null) {
mapView.onLowMemory();
}
}
}
阅读https://developers.google.com/maps/documentation/android-sdk/reference/com/google/android/libraries/maps/MapView了解更多详情。