将 FragmentActivity 转换为 Fragment

Posted

技术标签:

【中文标题】将 FragmentActivity 转换为 Fragment【英文标题】:Transform FragmentActivity to Fragment 【发布时间】:2020-02-22 17:04:13 【问题描述】:

我正在寻找将 FragmentActivity Map 示例转换为我的应用程序的 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;

    

这个应用片段是一张地图,我可以在其中跟随我的位置。 谢谢大家!

PS:这条线还不行:)

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

【问题讨论】:

【参考方案1】:
implements  OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener

类声明中缺少此代码。

【讨论】:

以上是关于将 FragmentActivity 转换为 Fragment的主要内容,如果未能解决你的问题,请参考以下文章

js将blob转换为文本

js将blob转换为文本

api 级别 11 以下设备的 FragmentActivity 类

使用hgimportsvn将SVN转换为Hg

将地址转换为纬度/经度(使用php)

FragmentActivity 无法解析为类型