项目中经常遇到ScrollView嵌套百度地图MapView,这时滑动百度地图时会发现水平左右方向可以滑动,上下滑动的时候就会发生冲突导致整个ScrollView一起滑动。
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!--其他组件-->
<com.baidu.mapapi.map.MapView
android:id="@+id/map_mapview"
android:layout_width="match_parent"
android:layout_height="220dp"
android:clickable="true" />
</LinearLayout>
</ScrollView>
解决方案
当滑动MapView时拦截父控件的触摸事件即可。
1、可以在MapView外嵌套一层自定义容器,重写事件分发。
public class MyMapView extends FrameLayout {
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
getParent().requestDisallowInterceptTouchEvent(true);//请求父控件不拦截触摸事件
} else if (ev.getAction() == MotionEvent.ACTION_UP) {
getParent().requestDisallowInterceptTouchEvent(false);
}
return super.dispatchTouchEvent(ev);
}
public MyMapView(Context context) {
super(context);
}
public MyMapView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyMapView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
2、在MapView外嵌套上MyMapView就可以随心所欲的滑动百度地图了~
<com.applib.widget.MyMapView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.baidu.mapapi.map.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="220dp" />
</com.applib.widget.MyMapView>