首页 > 解决方案 > 在片段上使用谷歌地图时,它不起作用,但在活动中使用相同的地图,为什么?

问题描述

下面我附上了我的片段类的代码,它没有显示我的地图,但是如果我将在活动中使用相同的 onMapReady() 代码,它工作得很好。我试过但还没有得到任何溶胶。我所做的是我更新了我的地图从 8.3.0 到 androidx(29.0.0)。我使用下面的片段仅在地图上显示当前位置。

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.location.Location;`
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdate;
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.LatLng;

import async_tasks.SosCheckinTrigger;
import helper_classes.GlobalFunctions;
import helper_classes.GlobalVariables;

public class EmergencyFragment extends Fragment implements OnMapReadyCallback {


    View rootView; // Root Layout for the Contact Agency
    private Context context;
    private Activity activity;
    private int REQUEST_PHONE = 2;
    public GoogleMap map;
    public Button checkInButton;
    public Button sosButton;
    String userID;
    String activePNRs;
    String currentPNR;

    protected GoogleApiClient mGoogleApiClient;

    protected Location mCurrentLocation;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.emergency, container, false);

        return rootView;
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        activity = getActivity();
        context = activity.getBaseContext();

        Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.tool_bar);
        TextView title = (TextView) toolbar.findViewById(R.id.title);
        title.setText(getResources().getString(R.string.emergency));
        title.setTypeface(Typeface.createFromAsset(context.getApplicationContext().getAssets(),
                "font/robotomedium.ttf"));

        ImageButton homemap = (ImageButton) toolbar.findViewById(R.id.home_map);
        homemap.setVisibility(View.VISIBLE);
        homemap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((AppCompatActivity) getActivity()).setTitle("");
                Fragment fragment = new NotificationsAndAlertsFragment();
                String name = "home";
                FragmentManager fragmentManager = ((AppCompatActivity) getActivity()).getSupportFragmentManager();
                fragmentManager.beginTransaction().replace(R.id.content, fragment, name).commit();
            }
        });

        TextView unread = (TextView) toolbar.findViewById(R.id.unread);

        try {
            SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
            userID = preferences.getString("userID", "");
        } catch (Exception e) {
            Log.e("getUserID", e.getMessage());
        }

        activePNRs = "";
        currentPNR = "";

        if (GlobalVariables.upcomingTripsList.size() > 0) {
            currentPNR = String.valueOf(GlobalVariables.upcomingTripsList.get(0).PnrID);
            for (int i = 0; i < GlobalVariables.upcomingTripsList.size(); i++) {
                if (activePNRs != "") {
                    activePNRs = activePNRs + "," + String.valueOf(GlobalVariables.upcomingTripsList.get(i).PnrID);
                } else {
                    activePNRs = String.valueOf(GlobalVariables.upcomingTripsList.get(i).PnrID);
                }
            }
        }


        sosButton = (Button) rootView.findViewById(R.id.send_sos_button);
        sosButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AlertDialog.Builder(activity)
                        .setTitle(getResources().getString(R.string.send_sos_button))
                        .setMessage(getResources().getString(R.string.send_sos_message))
                        .setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (GlobalFunctions.isNetworkAvailable(context)) {
                                    SosCheckinTrigger sosCheckinTrigger = new SosCheckinTrigger(activity, context, userID, "1", activePNRs, currentPNR);
                                    sosCheckinTrigger.execute();
                                } else {
                                    Toast.makeText(context, getResources().getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
                                }
                            }
                        }).setNegativeButton(getResources().getString(R.string.cancel_button_label), null).show();
                //return false;


            }
        });


        checkInButton = (Button) rootView.findViewById(R.id.check_in_button);
        checkInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AlertDialog.Builder(activity)
                        .setTitle(getResources().getString(R.string.check_in_safe_button))
                        .setMessage(getResources().getString(R.string.check_in_message))
                        .setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (GlobalFunctions.isNetworkAvailable(context)) {
                                    SosCheckinTrigger sosCheckinTrigger = new SosCheckinTrigger(activity, context, userID, "00", activePNRs, currentPNR);
                                    sosCheckinTrigger.execute();
                                } else {
                                    Toast.makeText(context, getResources().getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
                                }
                            }
                        }).setNegativeButton(getResources().getString(R.string.cancel_button_label), null).show();
                //return false;


            }
        });

        if (GlobalFunctions.Unread().equals("")) {
            unread.setVisibility(View.INVISIBLE);
        } else {
            unread.setText(GlobalFunctions.Unread());
        }

        SupportMapFragment fragment = (SupportMapFragment)
                getActivity().getSupportFragmentManager().findFragmentById(R.id.placeMap);

        if (fragment != null)
            fragment.getMapAsync(this);

    }

     public SupportMapFragment getMapFragment() {

        Log.i("check","map");
        FragmentManager fm = getChildFragmentManager();
        Fragment fragment = (SupportMapFragment) fm.findFragmentById(R.id.placeMap);
        if (fragment == null) {
            fragment = SupportMapFragment.newInstance();
            fm.beginTransaction().replace(R.id.placeMap, fragment).commit();
        }
        return (SupportMapFragment) fm.findFragmentById(R.id.placeMap);
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        map = googleMap;
        if (GlobalVariables.currentLocation != null) {
            mCurrentLocation = GlobalVariables.currentLocation;

            double lat = mCurrentLocation.getLatitude();
            double lang = mCurrentLocation.getLatitude();
            Log.e("LALNG",lat + lang + "");
            //LatLng loc = new LatLng(mCurrentLocation.getLatitude(),mCurrentLocation.getLongitude());
            LatLng sydney = new LatLng(28.644800, 77.216721);
            CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
            /*map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mCurrentLocation.getLatitude(),
                    mCurrentLocation.getLongitude()), 15));*/
            map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
            map.animateCamera(zoom);
        }
        if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), android.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;
        }
        map.setMyLocationEnabled(true);
        map.getUiSettings().setMyLocationButtonEnabled(true);


    }
}

标签: android

解决方案


检查我的要点,我认为您缺少将地图回调附加到生命周期onResume/////onStartonPauseonStoponDestroyViewonLowMemory

https://gist.github.com/pavelpoley/0253460cc21e2e779db61164332c7ee9


推荐阅读