57

我正在尝试将谷歌地图放在滚动视图中,以便用户可以向下滚动其他内容以查看地图。问题是这个滚动视图正在吃掉所有的垂直触摸事件,所以地图的 UI 体验变得很奇怪。

我知道在谷歌地图的 V1 中,您可以覆盖 onTouch 或 setOnTouchListener 以在 MotionEvent.ACTION_DOWN 上调用 requestDisallowInterceptTouchEvent。我试图用 V2 实现类似的技巧,但无济于事。

到目前为止,我已经尝试过:

  • 覆盖 SupportMapFragment,并在 onCreateView 内部,为 View 设置一个触摸监听器
  • 调用 SupportMapFragment 实例的 .getView(),然后调用 setOnTouchListener
  • 环绕相对布局或框架布局,用透明视图或图像视图屏蔽片段

这些都没有解决滚动问题。我在这里错过了什么吗?如果有人在滚动视图中有地图的工作示例,请您分享代码示例吗?

4

9 回答 9

150

在地图视图片段上应用透明图像。

<RelativeLayout
    android:id="@+id/map_layout"
    android:layout_width="match_parent"
    android:layout_height="300dp">

    <fragment
        android:id="@+id/mapview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="-100dp"
        android:layout_marginBottom="-100dp"
        android:name="com.google.android.gms.maps.MapFragment"/>

    <ImageView
        android:id="@+id/transparent_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@color/transparent" />

</RelativeLayout>   

然后设置requestDisallowInterceptTouchEvent(true)为主ScrollView。当用户触摸透明图像并移动时,禁用透明图像上的触摸,MotionEvent.ACTION_DOWN以便MotionEvent.ACTION_MOVE地图片段可以接受触摸事件。

ScrollView mainScrollView = (ScrollView) findViewById(R.id.main_scrollview);
ImageView transparentImageView = (ImageView) findViewById(R.id.transparent_image);

transparentImageView.setOnTouchListener(new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        switch (action) {
           case MotionEvent.ACTION_DOWN:
                // Disallow ScrollView to intercept touch events.
                mainScrollView.requestDisallowInterceptTouchEvent(true);
                // Disable touch on transparent view
                return false;

           case MotionEvent.ACTION_UP:
                // Allow ScrollView to intercept touch events.
                mainScrollView.requestDisallowInterceptTouchEvent(false);
                return true;

           case MotionEvent.ACTION_MOVE:
                mainScrollView.requestDisallowInterceptTouchEvent(true);
                return false;

           default: 
                return true;
        }   
    }
});

这对我有用。希望对你有帮助。。

于 2013-06-26T10:06:27.810 回答
18

我遇到了类似的问题,并根据上面的 In-Ho Yi 和 Данаил Димитров 的答案提出了一个更通用的工作解决方案。

public class CustomScrollView extends ScrollView {

    List<View> mInterceptScrollViews = new ArrayList<View>();

    public CustomScrollView(Context context) {
        super(context);
    }

    public CustomScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void addInterceptScrollView(View view) {
        mInterceptScrollViews.add(view);
    }

    public void removeInterceptScrollView(View view) {
        mInterceptScrollViews.remove(view);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {

        // check if we have any views that should use their own scrolling
        if (mInterceptScrollViews.size() > 0) {
            int x = (int) event.getX();
            int y = (int) event.getY();
            Rect bounds = new Rect();

            for (View view : mInterceptScrollViews) {
                view.getHitRect(bounds);
                if (bounds.contains(x, y + scrollY)) {
                    //were touching a view that should intercept scrolling
                    return false;
                }
            }
        }

        return super.onInterceptTouchEvent(event);
    }
}
于 2014-01-06T20:58:01.373 回答
9

谢谢你的建议,

经过多次尝试和错误,拔掉我的头发,对着显示器和我糟糕的 Android 测试手机发誓,我想如果我自定义 ScrollView,覆盖 onInterceptTouchEvent,当事件在地图视图上时我们返回 false 无论如何什么,那么地图上的滚动确实会按预期发生。

class MyScrollView(c:Context, a:AttributeSet) extends ScrollView(c,a) {
  val parent = c.asInstanceOf[MyActivity]
  override def onInterceptTouchEvent(ev:MotionEvent):Boolean = {
    var bound:Rect = new Rect()
    parent.mMap.getHitRect(bound)
    if(bound.contains(ev.getX.toInt,ev.getY.toInt))
      false
    else
      super.onInterceptTouchEvent(ev)
  }
}

这段代码在 Scala 中,但你明白了。

注意我最终使用了原始地图视图(如 android-sdks\extras\google\google_play_services\samples\maps\src\com\example\mapdemoRawMapViewDemoActivity.java 所示)。我猜你可以用片段做几乎同样的事情,我只是从一开始就不喜欢片段。

我认为谷歌欠我一个道歉。

于 2013-06-07T05:23:07.033 回答
5

我遇到了同样的问题,所以这是我将解决方案用作 java 代码的方式,以防万一有人需要它。您只需在使用时设置 mapView 字段。

import com.google.android.gms.maps.MapView;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ScrollView;

public class ScrollViewWithMap extends ScrollView
{
    public MapView mapView;

    public ScrollViewWithMap(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev)
    {
        if (mapView == null)
            return super.onInterceptTouchEvent(ev);

        if (inRegion(ev.getRawX(), ev.getRawY(), mapView))
            return false;

        return super.onInterceptTouchEvent(ev);
    }

    private boolean inRegion(float x, float y, View v)
    {
        int[] mCoordBuffer = new int[]
        { 0, 0 };

        v.getLocationOnScreen(mCoordBuffer);

        return mCoordBuffer[0] + v.getWidth() > x && // right edge
                mCoordBuffer[1] + v.getHeight() > y && // bottom edge
                mCoordBuffer[0] < x && // left edge
                mCoordBuffer[1] < y; // top edge
    }
}
于 2013-08-28T11:41:51.807 回答
4

在您的 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);
                    }
                });
            }
        });
于 2018-11-21T12:09:39.683 回答
1

如果您不再需要透明图像,请改进代码:

// gmap hack for touch and scrollview
        final ScrollView mainScrollView = (ScrollView) rootView.findViewById(R.id.scrollView);
        (rootView.findViewById(R.id.fixTouchMap)).setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        // Disallow ScrollView to intercept touch events.
                        mainScrollView.requestDisallowInterceptTouchEvent(true);
                        // Disable touch on transparent view
                        return false;

                    case MotionEvent.ACTION_UP:
                        // Allow ScrollView to intercept touch events.
                        mainScrollView.requestDisallowInterceptTouchEvent(false);
                        return true;

                    case MotionEvent.ACTION_MOVE:
                        mainScrollView.requestDisallowInterceptTouchEvent(true);
                        return false;

                    default:
                        return true;
                }
            }
        });
于 2015-08-20T17:28:36.237 回答
1

接受的答案在我的情况下不起作用。客人的回答都没有(但几乎)。如果其他人是这种情况,请尝试此编辑版本的访客答案。

如果有人在计算 hitbox 时需要使用它,我已经注释掉了操作栏高度。

public class InterceptableScrollView extends ScrollView {

    List<View> mInterceptScrollViews = new ArrayList<View>();

    public InterceptableScrollView(Context context) {
        super(context);
    }

    public InterceptableScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public InterceptableScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void addInterceptScrollView(View view) {
        mInterceptScrollViews.add(view);
    }

    public void removeInterceptScrollView(View view) {
        mInterceptScrollViews.remove(view);
    }

    private int getRelativeTop(View myView) {
        if (myView.getParent() == this)
            return myView.getTop();
        else
            return myView.getTop() + getRelativeTop((View) myView.getParent());
    }
    private int getRelativeLeft(View myView) {
        if (myView.getParent() == this)
            return myView.getLeft();
        else
            return myView.getLeft() + getRelativeLeft((View) myView.getParent());
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {

        // check if we have any views that should use their own scrolling
        if (mInterceptScrollViews.size() > 0) {
            int x = (int) event.getX();
            int y = (int) event.getY();


            /*
            int actionBarHeight = 0;

            TypedValue tv = new TypedValue();
            if (getContext().getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
            {
                actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
            }
            */

            int viewLocationY = 0;
            int viewLocationX = 0;
            int relativeTop = 0;
            int relativeLeft = 0;

            for (View view : mInterceptScrollViews) {

                relativeTop = getRelativeTop((View) view.getParent());
                relativeLeft = getRelativeLeft((View) view.getParent());
                viewLocationY = relativeTop - getScrollY();
                viewLocationX = relativeLeft - getScrollX();

                if (view.getHeight() + viewLocationY > y && y > viewLocationY && view.getWidth() + viewLocationX > x && x > viewLocationX)
                {
                    return false;
                }
            }
        }

        return super.onInterceptTouchEvent(event);
    }
}
于 2016-04-13T12:19:52.607 回答
0

上面列出的大多数选项对我来说都不起作用,但事实证明,以下选项对我来说是一个很好的解决方案:

奶酪男爵解决方案

对于我的实现,我还必须实现稍有不同,因为我在片段中使用地图,这使事情稍微复杂但易于工作。

于 2017-03-17T18:21:23.677 回答
0

@Laksh 答案的 Kotlin 版本:a) 实现 View.OnTouchListener,b) 将 onTouch 侦听器添加到活动的 onCreate 中的透明视图中。c) 重写函数如下:

override fun onTouch(v: View?, event: MotionEvent?): Boolean {
    when (v?.id) {
        R.id.transparent_image -> {

            when (event?.action) {
                MotionEvent.ACTION_DOWN -> {
                    reportScrollView.requestDisallowInterceptTouchEvent(true)
                    return false
                }
                MotionEvent.ACTION_UP -> {
                    reportScrollView.requestDisallowInterceptTouchEvent(false)
                    return true
                }
                MotionEvent.ACTION_MOVE -> {
                    reportScrollView.requestDisallowInterceptTouchEvent(true)
                    return false
                }
                else -> return true
            }
        }
        else -> {
            return true
        }
    }
}
于 2020-01-07T12:12:14.350 回答