覆盖MapView中的onTouchEvent

时间:2012-10-06 16:39:30

标签: android android-mapview android-activity

我想在scrollView中使用MapView。这样做会导致地图滚动问题,当你想滚动地图时,整个页面都会滚动。我在这里找到了解决这个问题的方法:MapView inside a ScrollView?
我创建了一个名为myMapView的类。这是代码:

package com.wikitude.example;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.google.android.maps.MapView;

public class myMapView extends MapView {

    public myMapView(Context context, String apiKey) {
        super(context, apiKey);
        // TODO Auto-generated constructor stub
    }

    public myMapView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public myMapView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        switch (action) {
        case MotionEvent.ACTION_DOWN:
            // Disallow ScrollView to intercept touch events.
            this.getParent().requestDisallowInterceptTouchEvent(true);
            break;

        case MotionEvent.ACTION_UP:
            // Allow ScrollView to intercept touch events.
            this.getParent().requestDisallowInterceptTouchEvent(false);
            break;
        }

        // Handle MapView's touch events.
        super.onTouchEvent(ev);
        return false;
    }
}

但是当我尝试在我的MapActivity中使用它时如下:

myMapView myview = (myMapView) findViewById(R.id.themap);

它会抛出此错误:
Undable to start activity ComponentInfo{com.smtabatabaie.example/com.smtabatabaie.mainActivity}: java.lang.ClassCastException: com.google.android.maps.MapView
我没有找到问题所在,似乎一切都没问题。如果有人可以帮助我,我将不胜感激 感谢

1 个答案:

答案 0 :(得分:3)

这就是你获得ClassCastException的原因。在您声明自定义mapview的XML文件中,您必须实际声明自定义mapview的名称,因此在您的情况下,它将是myMapView。这就是您的XML文件应该是这样的:

<com.wikitude.example.myMapView   //This is where you're probably going wrong (so what I've posted is the right way to declare it)
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mapview"
android:layout_width="fill_parent" //Replace these with whatever width and height you need
android:layout_height="fill_parent"
android:clickable="true"
android:apiKey="Enter-your-key-here"
/>