在片段中的对话片段内显示 google 地图

Show a google map inside a dialogfragment in a fragment

我想在从片段加载的对话框片段中加载地图。

当我使用 activity 执行此操作时,它工作正常,显示地图并且功能齐全。 但是,当我在片段内执行此操作时,地图仅显示左下角带有 google 徽标的灰色片段。

我到处浏览,几乎得到了一个类似的答案来检查我的 google API 密钥。但是,API 键在其他项目中运行良好。我也试过更改它,但没有帮助。

这是我的代码: map_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorPrimary">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Choose your location"
            android:textAlignment="center"
            android:padding="10dp"
            android:textAppearance="@style/TextAppearance.AppCompat.Headline" />
    </RelativeLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="10dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:text="Long click the marker pin or click anywhere on map"
            android:textAlignment="center"
            android:textSize="18dp" />

        <ScrollView android:id="@+id/ScrollView01"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <fragment xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="match_parent"
                    android:layout_height="250dp"
                    android:id="@+id/map"
                    tools:context=".ngo.NgoHomeActivity"
                    android:name="com.google.android.gms.maps.SupportMapFragment"
                    android:layout_marginTop="15dp"/>

                <customfonts.MyEditText
                    android:layout_marginTop="10dp"
                    android:padding="20dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:textColorHint="#000"
                    android:textColor="#000"
                    android:inputType="textMultiLine"
                    android:textSize="16dp"
                    android:hint="Address"
                    android:id="@+id/etAddress"/>
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="16dp"
                    android:id="@+id/btnSaveAddress"
                    android:text="SAVE ADDRESS"
                    android:background="@drawable/angle"
                    android:textColor="#fff"
                    android:gravity="center"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:padding="5dp"
                    android:layout_alignParentBottom="true"
                    android:layout_marginBottom="20dp"
                    android:layout_marginTop="10dp"/>
            </LinearLayout>

        </ScrollView>

    </LinearLayout>
</LinearLayout>

MapDialogFragment.java


public class MapDialogFragment extends DialogFragment implements OnMapReadyCallback{
    Address address;
    StringBuffer addressDetails;
    List<Address> addresses;
    GoogleMap mMap;
    Marker marker;

    Location currentLocation;
    LatLng latLng;
    FusedLocationProviderClient fusedLocationProviderClient;
    private static final int REQUEST_CODE = 101;
    double latitude, longitude;
    String nAddLine2;
    View rootView;
    EditText edAddress;
    Button btnSaveAdd;
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_map_dialog,container,false);
        edAddress = rootView.findViewById(R.id.etAddress);
        btnSaveAdd = rootView.findViewById(R.id.btnSaveAddress);
        btnSaveAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getDialog().dismiss();
            }
        });
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
        fetchLastLocation();
        return rootView;
    }
    @Override
    public void onMapReady(GoogleMap googleMap) {
        latLng = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
        mMap = googleMap;
        CameraPosition newCamPos = new CameraPosition(latLng,
                15.5f,
                mMap.getCameraPosition().tilt, //use old tilt
                mMap.getCameraPosition().bearing); //use old bearing
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(newCamPos), 4000, null);
//        mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,10));
        Toast.makeText(getContext(), latLng.toString(),Toast.LENGTH_LONG).show();

        mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
            @Override
            public void onMarkerDragStart(Marker marker) {

            }

            @Override
            public void onMarkerDrag(Marker marker) {

            }

            @Override
            public void onMarkerDragEnd(Marker marker) {
                Geocoder geocoder = new Geocoder(getContext(), Locale.getDefault());
                try{
                    latitude = marker.getPosition().latitude;
                    longitude = marker.getPosition().longitude;
                    addresses = geocoder.getFromLocation(latitude, longitude, 1);
                }catch (Exception IOException) {
                    IOException.printStackTrace();
                    Log.d("Error Message:", IOException.getMessage());
                    Log.e("", "Error in getting address for the location");
                    Toast.makeText(getContext(), "Couldn't get address",Toast.LENGTH_SHORT).show();
                }

                if(addresses == null || addresses.size() == 0){
                    Log.e("","Error in getting address for the location");

                }else{
                    String receivedAddress = getAddress();
                    showResults(receivedAddress);
                    mMap.animateCamera(CameraUpdateFactory.newLatLng(marker.getPosition()));
                }
            }
        });
        marker = mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .draggable(true));
    }

    private void fetchLastLocation() {
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
            return;
        }
        Task<Location> task = fusedLocationProviderClient.getLastLocation();
        task.addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if (location != null) {

                    currentLocation = location;
//                    Toast.makeText(getContext(), location.toString(),Toast.LENGTH_LONG).show();
                    SupportMapFragment supportMapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
                    supportMapFragment.getMapAsync(MapDialogFragment.this);
                }
            }
        });
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case REQUEST_CODE:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    fetchLastLocation();
                }
        }
    }

    public String getAddress(){

    }

    private void showResults(String currentAdd) {


    }
}

以及启动对话框片段的片段中的按钮 clcik 事件:

edNAddLine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new MapDialogFragment().show(getFragmentManager(),null);
            }
        });

有人能帮忙吗?

终于自己解决了这个问题。问题仅出在片段上。 因为我尝试在 activity 中启动地图并且它工作得很好。

对于遇到问题的人,我更改了以下语句:

dialogFragment.show(Objects.requireNonNull(getFragmentManager()),null);

关键在哪里:Objects.requireNonNull(getFragmentManager).

不过我不知道,那有什么用。感谢回答。