在您的 XML 中使用自定义 Google 地图片段。
这是对我有用的完整代码。如果你们有任何问题,请告诉我。
在您的 XML 文件中,添加以下内容作为地图片段
<fragment
android:id="@+id/map_with_scroll_fix"
android:name="com.myapplication.maputil.GoogleMapWithScrollFix"
android:layout_width="match_parent"
android:layout_height="match_parent" />
这是地图的自定义类
package com.myapplication.maputil;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.google.android.gms.maps.SupportMapFragment;
public class GoogleMapWithScrollFix extends SupportMapFragment {
private OnTouchListener mListener;
@Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstance) {
View layout = super.onCreateView(layoutInflater, viewGroup, savedInstance);
TouchableWrapper touchableWrapper = new TouchableWrapper(getActivity());
touchableWrapper.setBackgroundColor(getResources().getColor(android.R.color.transparent));
((ViewGroup) layout).addView(touchableWrapper,
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
return layout;
}
public void setListener(OnTouchListener listener) {
mListener = listener;
}
public interface OnTouchListener {
void onTouch();
}
public class TouchableWrapper extends FrameLayout {
public TouchableWrapper(Context context) {
super(context);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mListener.onTouch();
break;
case MotionEvent.ACTION_UP:
mListener.onTouch();
break;
}
return super.dispatchTouchEvent(event);
}
}
}
在您的活动类中添加以下内容,以初始化地图视图。就是这样。多田 :)
((GoogleMapWithScrollFix) getSupportFragmentManager()
.findFragmentById(R.id.map_with_scroll_fix)).getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
ScrollView mScrollView = findViewById(R.id.scrollview); //parent scrollview in xml, give your scrollview id value
((GoogleMapWithScrollFix) getSupportFragmentManager()
.findFragmentById(R.id.map_with_scroll_fix)).setListener(new GoogleMapWithScrollFix.OnTouchListener() {
@Override
public void onTouch() {
//Here is the magic happens.
//we disable scrolling of outside scroll view here
mScrollView.requestDisallowInterceptTouchEvent(true);
}
});
}
});