gpt4 book ai didi

java - 将 FragmentActivity 转换为 Fragment

转载 作者:行者123 更新时间:2023-12-02 09:22:38 25 4
gpt4 key购买 nike

我正在寻找将 FragmentActivity Map 示例转换为我的应用程序的 Fragment,我已经编辑了有关上下文或导入的所有内容。我只需要将新代码放入旧代码中,但我找不到位置...(我知道我很荒谬^^)

这是我的旧 fragment 代码,在我的手机中运行良好:

package com.example.discover;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import com.google.android.gms.location.LocationListener;

public class Maps_fragment extends Fragment {

private GoogleMap mMap;

private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager mLocationManager;
private LocationRequest mLocationRequest;
private com.google.android.gms.location.LocationListener listener;
private long UPDATE_INTERVAL = 2 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 20000; /* 20 sec */

private LocationManager locationManager;
private LatLng latLng;
private boolean isPermission;

public Maps_fragment() {
// Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_maps, container, false);

SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.maps); //use SuppoprtMapFragment for using in fragment instead of activity MapFragment = activity SupportMapFragment = fragment
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap mMap) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

mMap.clear(); //clear old markers

CameraPosition googlePlex = CameraPosition.builder()
.target(new LatLng(37.4219999,-122.0862462))
.zoom(10)
.bearing(0)
.tilt(45)
.build();

mMap.animateCamera(CameraUpdateFactory.newCameraPosition(googlePlex), 10000, null);

mMap.addMarker(new MarkerOptions()
.position(new LatLng(37.4629101,-122.2449094))
.title("Iron Man")
.snippet("His Talent : Plenty of money"));

mMap.addMarker(new MarkerOptions()
.position(new LatLng(37.3092293,-122.1136845))
.title("Captain America"));
}
});


return rootView;
}
}

我想添加这个:

    @Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

if (latLng != null) {
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker in Current Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
}

@Override
public void onConnected(@Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}

startLocationUpdates();

mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

if (mLocation == null) {
startLocationUpdates();
}
if (mLocation != null) {

// mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude()));
//mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude()));
} else {
Toast.makeText(getContext(), "Location not Detected", Toast.LENGTH_SHORT).show();
}
}

@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection Suspended");
mGoogleApiClient.connect();
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}

@Override
public void onLocationChanged(Location location) {
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
// mLatitudeTextView.setText(String.valueOf(location.getLatitude()));
// mLongitudeTextView.setText(String.valueOf(location.getLongitude()));
Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
// You can now create a LatLng Object for use with maps
latLng = new LatLng(location.getLatitude(), location.getLongitude());

// Obtain the SupportMapFragment and get notified when the map is ready to be used.
//it was pre written
//TODO assert getFragmentManager() != null;
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager()
.findFragmentById(R.id.maps);
//TODO assert mapFragment != null;
mapFragment.getMapAsync((OnMapReadyCallback) this);
}

protected void startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
// Request location updates
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, (LocationListener) this);
Log.d("reque", "--->>>>");
}

@Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}

@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}

private boolean checkLocation() {
if (!isLocationEnabled())
showAlert();
return isLocationEnabled();
}

private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {

Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {

}
});
dialog.show();
}

private boolean isLocationEnabled() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}

private boolean requestSinglePermission() {

Dexter.withActivity(getActivity())
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
@Override
public void onPermissionGranted(PermissionGrantedResponse response) {
//Single Permission is granted
Toast.makeText(getContext(), "Single permission is granted!", Toast.LENGTH_SHORT).show();
isPermission = true;
}

@Override
public void onPermissionDenied(PermissionDeniedResponse response) {
// check for permanent denial of permission
if (response.isPermanentlyDenied()) {
isPermission = false;
}
}

@Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();

return isPermission;

}
}

这个应用程序 fragment 是一张 map ,我可以在其中跟踪我的位置。谢谢大家!

PS:这条线还不能工作:)

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

最佳答案

implements  OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener

类声明中缺少此代码。

关于java - 将 FragmentActivity 转换为 Fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58573852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com