如何将视图添加到mapView上的特定点

时间:2011-06-30 16:37:10

标签: java android touch android-mapview

a当我的MapView上发生onTouch事件时,我希望我指定的布局被绘制在用户触摸的位置上方

以下是我开始的地方,我不知道如何将弹出视图放在从事件中检索到的x和y值上。你们有什么想法吗?

@Override
public boolean onTouchEvent(MotionEvent ev, MapView mapView) {

int X = (int)ev.getX();          
int Y = (int)ev.getY();

ViewGroup parent=(ViewGroup)map.getParent();
View popup=getLayoutInflater().inflate(R.id.popup, parent, false);

((ViewGroup)map.getParent()).addView(popup);

2 个答案:

答案 0 :(得分:0)

您可以使用x和y的值设置MapView.LayoutParams(),然后使用LayoutParams调用MapView的addView

MapView.LayoutParams params = new MapView.LayoutParams(width, height, x, y, alignment);
mapView.addView(popup, params);

答案 1 :(得分:0)

首先,您需要一个带有X,Y坐标的全局Point

@Override
public boolean onTouchEvent(MotionEvent ev, MapView mapView) {
    int X = (int)ev.getX();          
    int Y = (int)ev.getY();

    selectedPoint = new Point(X,Y);
    return true;
}

现在,您应该覆盖onDraw()方法以绘制弹出视图。有很多解决办法,我用StaticLayout尝试过这个:

@Override
public void draw (Canvas canvas, MapView mapView, boolean shadow){
    super.draw(canvas, mapView, false); 
    if ( selectedPoint != null) {

        // here you should define PopupText, textPaint and width variables

        StaticLayout sl = new StaticLayout(popupText, textPaint, width, 
                    Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);  

        // here you can draw a rectangle — border for your popup text. 
        // You can use sl.getWidth() and sl.getWidth() methods to get the popup dimensions  

        canvas.save();
        canvas.translate(selectedPoint.x, selectedPoint.y);
        sl.draw(canvas);
        canvas.restore()
    }
}