【发布时间】:2018-06-10 09:42:53
【问题描述】:
我在fragment 内使用SupportMapFragment,第一次显示地图,但第二次进入该片段时,地图变为白色且不显示。
我尝试了多种解决方案,包括:删除以前的 fragment ,覆盖 onDestroy() 和 onPause(),但徒劳无功。
一个简单的问题:我应该使用MapView 而不是SupportMapFragment 吗?
任何帮助将不胜感激,因为我已经为此苦苦挣扎了好几天。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
view = inflater.inflate(R.layout.rider_fragment_home, container, false);
} catch (InflateException e) {
}
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle
savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.onCreate(savedInstanceState);
mapFragment.getMapAsync(this);
setUpLocation();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setIndoorEnabled(false);
mMap.setTrafficEnabled(false);
mMap.setBuildingsEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(true);
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(getActivity().getBaseContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity().getBaseContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (mGoogleApiClient != null) {
Common.mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if ( Common.mLastLocation != null) {
final double latitude = Common.mLastLocation.getLatitude();
final double longitude = Common.mLastLocation.getLongitude();
//update to database (TO_DO)
if (mCurrent != null) {
mCurrent.remove(); // remove actual marker
}
mCurrent = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.driver_marker))
.position(new LatLng(latitude, longitude))
.title("You"));
//move camera to the new position
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 7.0f));
}
}
}
private void startLocationUpdates() {
//ACCESS_COARSE_LOCATION : approximate location
//ACCESS_FINE_LOCATION : exact location
if (ActivityCompat.checkSelfPermission(getActivity().getBaseContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity().getBaseContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (mGoogleApiClient != null) {
//requestLactionUpdates : register the current activity to be updated periodically
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
displayLocation();
startLocationUpdates();
}
@Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
Common.mLastLocation = location;
displayLocation();
if (Common.mLastLocation != null) {
new LocationService().LocationUser(getActivity(), Common.mLastLocation.getLatitude() + "", Common.mLastLocation.getLongitude() + "", LoginFragment.user.getUserID());
//update last seen location
String lat = String.valueOf(Common.mLastLocation.getLatitude());
String lng = String.valueOf(Common.mLastLocation.getLongitude());
}
}
@Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class
.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
public void onResume() {
super.onResume();
mapFragment.onResume();
}
@Override
public void onPause() {
super.onPause();
mapFragment.onPause();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (checkPlayServices()) {
buildGoogleApiClient();
createLocationRequest();
displayLocation();
}
}
}
}
private void setUpLocation() {
if (ActivityCompat.checkSelfPermission(getActivity().getBaseContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity().getBaseContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
}, MY_PERMISSION_REQUEST_CODE);
} else {
if (checkPlayServices()) {
buildGoogleApiClient();
createLocationRequest();
displayLocation();
}
}
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity().getApplicationContext());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
//if their is an error and it's recoverable , an error dialog is shown to tell the user about error and direct them to playStore if Google Play services is out of date or missing
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(), PLAY_SERVICE_RES_REQUEST).show();
} else {
Toast.makeText(getActivity().getApplicationContext(), "This device is not supported", Toast.LENGTH_SHORT).show();
}
return false;
}
return true;
}
【问题讨论】:
-
你的代码在哪里
-
请发布您的
fragment代码,我们无法在不显示您的代码的情况下建议您 -
对不起,我更新了问题。
标签: android google-maps dictionary android-fragments supportmapfragment