Кнопки управления картой Google (такие как mylocation et c) исчезают при реализации в фрагменте - PullRequest
0 голосов
/ 22 марта 2020

Я использовал Google map API в приложении android, я использовал навигацию с вкладками, которая состоит из трех фрагментов, я внедрил карты Google в один из фрагментов, но теперь я не вижу кнопок управления. Я перепробовал все, включая перемещение кнопок управления, но ни одна из них не помогла.

Вот моя java активность MapActivity

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {
    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    LocationRequest mLocationRequest;
    View mapView;
    private GoogleMap mMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkLocationPermission();
        }
        SupportMapFragment mapFragment = (SupportMapFragment)
                getSupportFragmentManager()
                        .findFragmentById(R.id.map);
        mMap.setMyLocationEnabled(true);
    mapView = mapFragment.getView();
        mapFragment.getMapAsync(this);
    }
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setZoomGesturesEnabled(true);
        mMap.getUiSettings().setCompassEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);
            }
        } else {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
        if (mapView != null &&
                mapView.findViewById(Integer.parseInt("1")) != null) {
            // Get the button view
            View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
            // and next place it, on bottom right (as Google Maps app)
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
                    locationButton.getLayoutParams();
            // position on right bottom
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
            layoutParams.setMargins(0, 100, 0, 0);
        }


    }
    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }
    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
//            LocationServices.requestLocationUpdates(mGoogleApiClient,
//                    mLocationRequest, (com.google.android.gms.location.LocationListener) this);
            LocationServices.getFusedLocationProviderClient(this);
        }

    }
    @Override
    public void onConnectionSuspended(int i) {
    }
    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }
//Showing Current Location Marker on Map
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        LocationManager locationManager = (LocationManager)
                getSystemService(Context.LOCATION_SERVICE);
        String provider = locationManager.getBestProvider(new Criteria(), true);
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Location locations = locationManager.getLastKnownLocation(provider);
        List<String> providerList = locationManager.getAllProviders();
        if (null != locations && null != providerList && providerList.size() > 0) {
            double longitude = locations.getLongitude();
            double latitude = locations.getLatitude();
            Geocoder geocoder = new Geocoder(getApplicationContext(),
                    Locale.getDefault());
            try {
                List<Address> listAddresses = geocoder.getFromLocation(latitude,
                        longitude, 1);
                if (null != listAddresses && listAddresses.size() > 0) {
                    String state = listAddresses.get(0).getAdminArea();
                    String country = listAddresses.get(0).getCountryName();
                    String subLocality = listAddresses.get(0).getSubLocality();
                    markerOptions.title("" + latLng + "," + subLocality + "," + state
                            + "," + country);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
        mCurrLocationMarker = mMap.addMarker(markerOptions);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
                    (com.google.android.gms.location.LocationListener) this);
        }
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
    }
    public boolean checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            } else {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            return true;
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {
                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mMap.setMyLocationEnabled(true);
                    }
                } else {
                    Toast.makeText(this, "permission denied",
                            Toast.LENGTH_LONG).show();
                }
                return;
            }
        }
    }
}

Вот мой фрагмент. xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout

    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MapsActivity" />


    <androidx.cardview.widget.CardView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:cardCornerRadius="15dp"
        android:padding="15dp"
        android:paddingStart="15dp"
        android:paddingEnd="15dp"

        android:elevation="20dp"
        app:cardElevation="10dp"
        android:layout_centerHorizontal="true"
        android:layout_alignTop="@+id/scroll"
        android:layout_marginTop="-450dp"
        android:background="#FFFFFF">

        <com.tomer.fadingtextview.FadingTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:texts="@array/panic"
            android:padding="10dp"
            android:textSize="25sp"
            android:textColor="#FF0000"
            android:textStyle="bold"
            app:timeout="500">


        </com.tomer.fadingtextview.FadingTextView>
    </androidx.cardview.widget.CardView>

    <com.akscorp.overscrollablescrollview.OverscrollableNestedScrollView
        android:layout_below="@+id/map"
        android:id="@+id/scroll"
        android:layout_marginTop="-200dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/form">

            <TextView
                android:id="@+id/text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"

                android:textColor="@color/colorPrimaryDark"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="35dp"
                android:textSize="16sp"
                android:textStyle="bold"/>

            <TextView
                android:layout_below="@+id/text"
                android:id="@+id/text2"
                android:layout_marginTop="20dp"
                android:layout_marginStart="20dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="POSITIVE:- "
                android:textStyle="bold"
                android:textSize="20sp"
                android:textColor="#FF0000"/>

            <TextView
                android:layout_width="wrap_content"
                android:id="@+id/text4"
                android:layout_height="wrap_content"
                android:layout_below="@+id/text"
                android:layout_centerHorizontal="true"
                android:layout_alignEnd="@+id/text2"
                android:layout_marginEnd="-30dp"
                android:layout_marginTop="20dp"
                android:text="0"
                android:textSize="20sp"
                android:textStyle="bold" />
            <TextView
                android:layout_below="@+id/text2"
                android:id="@+id/text3"
                android:layout_marginTop="20dp"
                android:layout_marginStart="20dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="NEGATIVE:- "
                android:textStyle="bold"
                android:textSize="20sp"
                android:textColor="#00EF7A"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/text4"
                android:layout_centerHorizontal="true"
                android:layout_alignEnd="@+id/text2"
                android:layout_marginEnd="-30dp"
                android:layout_marginTop="20dp"
                android:text="0"
                android:textSize="20sp"
                android:textStyle="bold" />

            <com.tomer.fadingtextview.FadingTextView
                android:id="@+id/fadingText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/text4"
                android:layout_marginTop="57dp"
                android:gravity="center"
                android:textColor="#E38308"
                android:textSize="20sp"
                android:textStyle="bold"
                app:texts="@array/text"
                app:timeout="500"/>

        </RelativeLayout>



    </com.akscorp.overscrollablescrollview.OverscrollableNestedScrollView>



</RelativeLayout>

1 Ответ

0 голосов
/ 23 марта 2020

Ваши кнопки не отображаются из-за того, что width_and_height фрагмента карты соответствует ширине родительского width_and_height.

<RelativeLayout
    ...
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    ...
    tools:context=".MapsActivity">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
    ...
        android:layout_width="match_parent"
        android:layout_height="match_parent"
    ...
        tools:context=".MapsActivity" />


Одно решение можно увидеть в примере ниже. Высота карты будет соответствующим образом скорректирована в зависимости от содержимого внутри LinearLayout.


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

  <LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_weight="1"
    android:layout_height="0dp">

    <fragment
      android:id="@+id/map"
      android:name="com.google.android.gms.maps.SupportMapFragment"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      tools:context=".MapsActivity" />

  </LinearLayout>

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

    <com.tomer.fadingtextview.FadingTextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:texts="@array/panic"
      android:padding="10dp"
      android:textSize="25sp"
      android:textColor="#FF0000"
      android:textStyle="bold"
      app:timeout="500"/>

  </LinearLayout>

</LinearLayout>

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...