在很多APP中,我们接入了百度地图,而这个百度地图只是拥有提示、展示的作用,并不希望它具有操作功能。
比如,在外卖APP中,粗略地展示一下地理位置,点击地图后,直接跳转对应的导航。
于是这样写到
<androidx.cardview.widget.CardView android:id="@+id/cv_map" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:clickable="true" android:focusable="true" android:focusableInTouchMode="true" app:cardBackgroundColor="@color/white" app:cardCornerRadius="8dp"> <com.baidu.mapapi.map.TextureMapView android:id="@+id/mapView" android:layout_width="match_parent" android:layout_height="120dp" />
</androidx.cardview.widget.CardView>
为Baidu地图包了一层CardView来设置圆角效果。然后点击这个地图时,执行操作。
cv_map?.setOnClickListener{ v -> // do something
}
却发现这个事件不能被响应,因为事件是会先被Baidu地图消费掉,如果不知道为什么可以看一下ViewGroup 事件分发。ViewGroup自己的点击事件是没有子View响应的情况下才会响应。
那么如果解决这个问题呢?
第1种方案、直接通过百度地图的点击事件进行操作
mapView?.map?.setOnMapClickListener(object : BaiduMap.OnMapClickListener{ override fun onMapClick(p0: LatLng?) { // 实现其他功能} override fun onMapPoiClick(p0: MapPoi?) { }
})
百度地图提供了Map的点击功能,可以直接通过此方法进行处理。
这种只适合点击地图产生行为的情况。
第2种方案,在百度地图上再设置一个View,使用该View的点击事件
<androidx.cardview.widget.CardView android:id="@+id/cv_map" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:clickable="true" android:focusable="true" android:focusableInTouchMode="true" app:cardBackgroundColor="@color/white" app:cardCornerRadius="8dp"> <com.baidu.mapapi.map.TextureMapView android:id="@+id/mapView" android:layout_width="match_parent" android:layout_height="120dp" /><Viewandroid:id="@+id/mapClickView"android:layout_width="match_parent" android:layout_height="120dp"/>
</androidx.cardview.widget.CardView>
然后,对View进行点击事件设置
mapClickView?.setOnClickListener{ v -> // do something
}
第3种方案,创建一个容器,屏蔽百度地图对事件的响应(看情况应用)
此时可以,通过创建一个内部View用于屏蔽事件传递给地图。
class NoTouchViewWrapper : FrameLayout{ constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) override fun dispatchTouchEvent(ev: MotionEvent?): Boolean { return false }
}
在xml中,将它套在地图外边即可
<com.huixian.biz.km.customer.widget.NoTouchViewWrapper android:layout_width="match_parent" android:layout_height="wrap_content"> <com.baidu.mapapi.map.TextureMapView android:id="@+id/mapView" android:layout_width="match_parent" android:layout_height="120dp" />
</com.huixian.biz.km.customer.widget.NoTouchViewWrapper>
这样百度地图不会抢夺点击事件了。