在安卓工作室中与其他小部件一起显示地图视图



请我需要帮助,我一直在努力解决这个问题,我想显示一个 MapView、一个按钮和两个文本视图。我已经尽我所能,看了很多教程,但仍然没有弄清楚,我想要的不是屏幕上显示的内容,地图显示得很好,但其他小部件没有显示,地图顶部出现一个搜索栏我不知道如何摆脱。并且我提前为我糟糕的代码编写道歉,我不是专家。请帮忙。谢谢。

布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/White"
android:id="@+id/relTest">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100"
android:background="@color/White">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="50"
android:id="@+id/map_container">
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map" />

</RelativeLayout>
<LinearLayout
android:id="@+id/info_tab"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="50"
android:orientation="vertical"
android:visibility="visible">
<ImageButton
android:layout_width="35dp"
android:layout_height="35dp"
android:src="@drawable/ic_full_screen_black_24dp"
android:background="@color/White"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:id="@+id/btn_full_screen_map"/>
<Button
android:id="@+id/online_offline_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_weight="2"
android:background="#0033cc"
android:padding="5dp"
android:text="Go Online"
android:textSize="15sp"
android:textStyle="bold" />

<TextView
android:id="@+id/score_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_weight="2"
android:background="@color/green1"
android:padding="5dp"
android:text="Player Score"
android:textAlignment="center"
android:textSize="30sp"
android:textStyle="bold" />
<TextView
android:id="@+id/rating_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_weight="2"
android:background="@color/green1"
android:padding="5dp"
android:text="Rating"
android:textAlignment="center"
android:textSize="30sp"
android:textStyle="bold" />
</LinearLayout>

</LinearLayout>

<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressBar"
android:layout_centerInParent="true"
android:visibility="gone"/>
</RelativeLayout>```

#MapActivity 

public class MapActivity extends FragmentActivity implements OnMapReadyCallback,
View.OnClickListener,
GoogleMap.OnInfoWindowClickListener {
//firestore access for cloud storage
FirebaseStorage storage = FirebaseStorage.getInstance();
private static final String TAG = "MapActivity";
private static final int ERROR_DIALOG_REQUEST = 9001;
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private boolean mLocationPermissionGranted = false;
private static final int LOCATION_PERMISSIONS_REQUEST_CODE = 1234;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private static final float DEFAULT_ZOOM = 17f;
private WorkerLocation mUserLocation;
private FusedLocationProviderClient mFusedLocationClient;
private boolean markerPinned;

//for adding a custom marker
private BitmapDescriptor bitmapDescriptorFromVector(Context context, int vectorResId) {
Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorResId);
vectorDrawable.setBounds(0, 0, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight());
Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
vectorDrawable.draw(canvas);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
//vars
private FirebaseFirestore mDb;
private GoogleMap map;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
//getLocationPermission();
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mDb = FirebaseFirestore.getInstance();
markerPinned = false;
if (Build.VERSION.SDK_INT >= 26) {
String CHANNEL_ID = "my_channel_01";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"MY Channel",
NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
NotificationManager notificationManager = null;
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("")
.setContentText("").build();
}
initMap();
}

@Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "onMapReady: map is ready here");
//Toast.makeText(this, "Map is ready", Toast.LENGTH_SHORT).show();
mMap = googleMap;
mMap.setMyLocationEnabled(true);
if (mMap.getUiSettings().isMapToolbarEnabled()) {
mMap.getUiSettings().setMapToolbarEnabled(false);
}
getDeviceLocation();
}
private void getLastKnownLocation() {
Log.d(TAG, "getLastKnownLocation: called.");

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<android.location.Location>() {
@Override
public void onComplete(@NonNull Task<android.location.Location> task) {
if (task.isSuccessful()) {
Location location = task.getResult();
GeoPoint geoPoint = new GeoPoint(location.getLatitude(), location.getLongitude());
mUserLocation.setGeoPoint(geoPoint);
mUserLocation.setTimeStamp(null);
saveUserLocation();
startLocationService();
}
}
});
}
private void getUserDetails(){
if(mUserLocation == null){
mUserLocation = new WorkerLocation();
DocumentReference userRef = mDb.collection("User locations")
.document(FirebaseAuth.getInstance().getUid());
userRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
Log.d(TAG, "onComplete: successfully set the user client.");
User user = task.getResult().toObject(User.class);
mUserLocation.setUser(user);
((UserClient)getApplicationContext()).setUser(user);
getLastKnownLocation();
}
}
});
}
else{
getLastKnownLocation();
}
}

private void saveUserLocation(){
if(mUserLocation != null){
DocumentReference locationRef = mDb.collection("User location")
.document(FirebaseAuth.getInstance().getUid());
locationRef.set(mUserLocation).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Log.d(TAG, "saveUserLocation: ninserted user location into database." +
"n latitude: " + mUserLocation.getGeoPoint().getLatitude() +
"n longitude: " + mUserLocation.getGeoPoint().getLongitude());
}
}
});
}
}
@Override
protected void onResume() {
super.onResume();
if(checkMapServices()){
if(mLocationPermissionGranted){
getUserDetails();
}
else{
getLocationPermission();
}
}
}
private boolean checkMapServices(){
if(isServicesOk()){
if(isMapsEnabled()){
return true;
}
}
return false;
}
public boolean isMapsEnabled(){
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
buildAlertMessageNoGps();
return false;
}
return true;
}

private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("This application requires GPS to work properly, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
Intent enableGpsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(enableGpsIntent, PERMISSIONS_REQUEST_ENABLE_GPS);
}
});
final AlertDialog alert = builder.create();
alert.show();
}

public boolean isServicesOk() {
Log.d(TAG, "isServicesOk: checking google services version");
int available = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(MapActivity.this);
if (available == ConnectionResult.SUCCESS) {
//everything is ok and the user can make a map request
Log.d(TAG, "isServicesOk: Google play services is working");
return true;
} else if (GoogleApiAvailability.getInstance().isUserResolvableError(available)) {
//an error occured but we can resolve it
Log.d(TAG, "isServicesOk: an error occured but we can fix it");
Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(MapActivity.this, available, ERROR_DIALOG_REQUEST);
dialog.show();
} else {
Toast.makeText(this, "You can't make map request", Toast.LENGTH_SHORT).show();
}
return false;
}

private void getDeviceLocation() {
Log.d(TAG, "getDeviceLocation: getting the device current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try {
if (mLocationPermissionGranted) {// check first to see if the permission is granted
Task<Location> location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
if (task.isSuccessful()) {
Log.d(TAG, "onComplete: Location found");
Location currentLocation = task.getResult();
//move camera to current location on map
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), DEFAULT_ZOOM, "My location");
} else {
Log.d(TAG, "onComplete: current location null");
Toast.makeText(MapActivity.this, "Could not get current location, make sure location is enagbled", Toast.LENGTH_SHORT).show();
}
}
});
}
} catch (SecurityException e) {
Log.d(TAG, "getDeviceLocation: SecurityException:" + e.getMessage());
}
}
private void moveCamera(LatLng latlng, float zoom, String title) {
Log.d(TAG, "moveCamera: moving camera to current latitude:" + latlng.latitude + " longitude" + latlng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, zoom));
//create a marker to drop pin at the location
MarkerOptions options = new MarkerOptions().position(latlng);
if (markerPinned) {
mMap.addMarker(options.position(latlng)).setIcon(bitmapDescriptorFromVector(getApplicationContext(), R.drawable.user));
} else {
initMap();
mMap.addMarker(options).setIcon(bitmapDescriptorFromVector(getApplicationContext(), R.drawable.user));
markerPinned = true;
}
}

private void initMap() {// for initializing the map
Log.d(TAG, "initMap: initializing map");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapActivity.this);

}
private void getLocationPermission() {
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this.getApplicationContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(), COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
getUserDetails();
initMap();// if the location permission is granted
} else {
Log.d(TAG, "getLocationPermission: Location permission failed");
ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSIONS_REQUEST_CODE);
}
} else {
Log.d(TAG, "getLocationPermission: Location permission failed");
ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSIONS_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case LOCATION_PERMISSIONS_REQUEST_CODE: {
if (grantResults.length > 0) {// that means some kind of permission was granted
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = false;
Log.d(TAG, "onRequestPermission: permission request failed");
return;
}
}
Log.d(TAG, "onRequestPermission: permission granted");
mLocationPermissionGranted = true;
//initialize our map
initMap();
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult: called.");
switch (requestCode) {
case PERMISSIONS_REQUEST_ENABLE_GPS: {
if(mLocationPermissionGranted){
getUserDetails();
}
else{
getLocationPermission();
}
}
}
}
private void startLocationService() {
Log.d(TAG, "startLocationService: Start of location service method");
if (!isLocationServiceRunning()) {
Intent serviceIntent = new Intent(MapActivity.this, LocationService.class);
this.startService(serviceIntent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
MapActivity.this.startForegroundService(serviceIntent);
} else {
startService(serviceIntent);
}
}
}
private boolean isLocationServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.example.zts.services.LocationService".equals(service.service.getClassName())) {
Log.d(TAG, "isLocationServiceRunning: location service is already running.");
return true;
}
}
Log.d(TAG, "isLocationServiceRunning: location service is not running.");
return false;
}
}
[![what I want when I run the application][1]][1]

[![what shows up when I run the app on the emulator][2]][2]

[1]: https://i.stack.imgur.com/bTImR.jpg
[2]: https://i.stack.imgur.com/evKfW.jpg

无法创建整个布局,但我下面是我为自定义我的地图视图设计而创建的布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:elevation="10dp"
android:background="@drawable/white_border"
android:id="@+id/relLayout1">
<ImageView
android:layout_width="15dp"
android:layout_height="15dp"
android:id="@+id/ic_magnify"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:src="@drawable/ic_magnify"/>
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="@+id/ic_magnify"
android:layout_centerVertical="true"
android:textSize="15sp"
android:textColor="#000"
android:id="@+id/input_search"
android:background="@null"
android:hint="Enter Address, City or Zip Code"
android:imeOptions="actionSearch"/>

</RelativeLayout>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_below="@id/relLayout1"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:scaleType="centerCrop"
android:id="@+id/ic_gps"
android:src="@drawable/ic_gps"/>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_below="@+id/relLayout1"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:scaleType="centerCrop"
android:id="@+id/place_info"
android:src="@drawable/ic_info"/>

可绘制/white_boarder.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#fff"/>
<corners android:radius="5dp"/>
</shape>
</item>
</layer-list>

最后,如果你想禁用地图的defult小部件,你可以用getUiSettings((来做。

yourMap.getUiSettings().setMyLocationButtonEnabled(false);

最新更新