你的问题实际上与用户体验有关,而不是与你的代码有关。
你可以使用两种解决方案,告诉用户应用正在执行某项操作,而不是只是卡住或崩溃:
解决方案1
可以使用一个加载视图,在加载信息时显示该视图,而不是显示地图。
<FrameLayout
<!-- same layout information as your current MapView -->
...
>
<MapView
...
/>
<View
<!-- This can be a ProgressBar or a custom loading View with animation -->
/>
</FrameLayout>
你可以在数据加载时将View设为
Visible
,然后等到地图加载完成后再显示。这样可以避免黑屏的问题。
更新:
根据这个
答案,你可以扩展一个
Fragment
并添加一个
MapView
。
设置用于显示地图的布局。
location_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.google.android.gms.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<View
android:id="@+id/loadingView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
现在我们编写用于显示地图的Java类。
MapViewFragment:
public class MapViewFragment extends Fragment {
MapView mMapView;
View mLoadingView;
private GoogleMap googleMap;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.location_fragment, container, false);
mMapView = (MapView) rootView.findViewById(R.id.mapView);
mLoadingView = rootView.findViewById(R.id.loadingView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
googleMap.setMyLocationEnabled(true);
LatLng sydney = new LatLng(-34, 151);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return rootView;
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
这样你就可以在获取数据后随时隐藏/显示
loadingView
。
解决方案2
在加载数据之前,您可以只显示地图,然后在获取数据时在其上方显示
ProgressBar
。一旦数据加载完成,您就可以填充地图。