我需要在FragmentActivity中使用getActivity()和getContext()方法。怎么做?我无法扩展Fragment类(我现在不能这样做)。也许我可以施放或其他东西。需要在这堂课中完成。
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private LatLng latLng;
private Marker currLocationMarker;
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
buildGoogleApiClient();
}
private synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this.getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public void onConnected(@Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this.getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this.getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
android.Manifest.permission.ACCESS_FINE_LOCATION
},
100);
return;
}
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
//place marker at current position
//mGoogleMap.clear();
latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
currLocationMarker = mMap.addMarker(markerOptions);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(latLng, 5);
mMap.animateCamera(yourLocation);
}
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000); //5 seconds
mLocationRequest.setFastestInterval(3000); //3 seconds
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setSmallestDisplacement(0.1F); //1/10 meter
}
}
答案 0 :(得分:2)
getActivity()和getContext()是严格的Fragment方法。由于FragmentActivity类扩展了Activity类,因此替代方案是'这个'和' getApplicationContext()'分别
e.g。
mGoogleApiClient = new GoogleApiClient.Builder(this.getContext())
可以成为,简单
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
答案 1 :(得分:0)
您无法做到这一点,因为FragmentActivity是一项活动。因此,您可以使用this
来访问您的上下文。
使用此:
this.getResources()
而不是
getContext.getResources()