Mapbox Android中Floating Action Button无法显示问题求助
问题分析与解决方案
你的FAB在运行时不显示,核心有两个问题:
1. 错误加载了空的MapView而非完整布局
你在onCreate里先通过ActivityMapsBinding加载了XML布局,但随后手动创建了一个全新的MapView实例,并把这个空的MapView设置为Activity的内容视图,完全忽略了XML里包含FAB的完整布局结构。
2. FAB嵌套位置错误
MapView本身不是ViewGroup,不能直接在它内部嵌套子View,必须把FAB放在与MapView同级的父布局中,才能让FAB显示在地图上方。
修改步骤
第一步:修正activity_maps.xml布局
把FAB从MapView内部移出来,和MapView同级放在CoordinatorLayout中:
<?xml version="1.0" encoding="utf-8"?> <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:mapbox="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <com.mapbox.maps.MapView android:id="@+id/mapView" android:layout_width="match_parent" android:layout_height="match_parent" mapbox:mapbox_cameraTargetLat="40.7128" mapbox:mapbox_cameraTargetLng="-74.0060" mapbox:mapbox_cameraZoom="9.0"/> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:backgroundTint="@color/purple_200" android:layout_margin="16dp" android:contentDescription="@string/fab_description" android:src="@drawable/ic_plus_icon" tools:ignore="ImageContrastCheck" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>
第二步:修正MapsActivity.kt的onCreate方法
移除手动创建MapView的代码,通过Binding获取布局里的MapView,并设置完整布局为内容视图:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMapsBinding.inflate(layoutInflater) // 移除手动创建MapView的代码 mapView = binding.mapView // 从Binding中获取XML里定义的MapView setContentView(binding.root) // 设置完整的布局根视图 locationInitHelper = LocationInitHelper(WeakReference(this)) locationInitHelper.setMapView(mapView) mapView.getMapboxMap().loadStyleUri(Style.MAPBOX_STREETS) locationEngine = LocationEngineProvider.getBestLocationEngine(this) locationPermissionHelper = LocationPermissionHelper(WeakReference(this)) onMapReady() }
内容的提问来源于stack exchange,提问作者Nirmal Purohit
相关产品推荐
相关产品推荐

