我正在try 用新的谷歌 map API v2点击一个标记,然后定制InfoWindow.我希望它看起来像谷歌最初的 map 应用程序.这样地:

示例图像

当我有ImageButton个在里面时,它就不起作用了——整个InfoWindow个都被删掉了,而不仅仅是ImageButton个.我读到这是因为它本身没有View,而是快照,所以单个项目无法相互区分.

EDIT:documentation名中(感谢Disco S2名):

如前一节"信息窗口"所述,信息窗口

但如果谷歌使用它,肯定有办法做到这一点.有人知道吗?

推荐答案

我自己也在寻找解决这个问题的方法,但运气不佳,所以我不得不推出自己的解决方案,我想在这里与大家分享.(请原谅我英语不好)(用英语回答另一个捷克人有点疯狂:-)

我try 的第一件事是用一台很好的旧PopupWindow.这很简单--人们只需听OnMarkerClickListener,然后在标记上方显示一个自定义的PopupWindow.StackOverflow上的其他一些人建议了这个解决方案,乍一看,它看起来相当不错.但是当你开始移动 map 时,这个解决方案的问题就会显现出来.你必须以某种方式自己移动PopupWindow,这是可能的(通过监听一些OnTouch事件),但我不能让它看起来足够好,特别是在一些速度较慢的设备上.如果你用简单的方式做,它就会从一个地方"跳"到另一个地方.你也可以使用一些动画来润色那些 skip ,但是这样的话,PopupWindow号将总是"落后一步",它应该在 map 上,这是我不喜欢的.

在这一点上,我在考虑其他的解决方案.我意识到我实际上并不需要太多的自由--显示我的自定义视图以及随之而来的所有可能性(比如动画进度条等).我认为,即使是谷歌工程师在谷歌 map 应用程序中也不这样做,这是有充分理由的.我所需要的只是InfoWindow上的一个或两个按钮,它将显示按下状态,并在单击时触发一些操作.所以我想出了另一个解决方案,它分成两个部分:

First part:
第一部分是能够捕捉按钮上的单击以触发某些操作.我的 idea 如下:

  1. 保留对InfoWindowAdapter中创建的自定义infoWindow的引用.
  2. MapFragment(或MapView)包装在自定义视图组中(我的视图组称为MapWrapperLayout)
  3. 覆盖MapWrapperLayout的dispatchTouchEvent(如果当前显示了InfoWindow),首先将MotionEvents路由到之前创建的InfoWindow.如果它不使用MotionEvents(比如,因为你没有点击信息窗口中的任何可点击区域等等),那么(并且只有在那时)让事件进入MapWrapperLayout的超类,这样它最终会被传递到 map .

以下是MapWrapperLayout的源代码:

package com.circlegate.tt.cg.an.lib.map;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.Marker;

import android.content.Context;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

public class MapWrapperLayout extends RelativeLayout {
    /**
     * Reference to a GoogleMap object 
     */
    private GoogleMap map;

    /**
     * Vertical offset in pixels between the bottom edge of our InfoWindow 
     * and the marker position (by default it's bottom edge too).
     * It's a good idea to use custom markers and also the InfoWindow frame, 
     * because we probably can't rely on the sizes of the default marker and frame. 
     */
    private int bottomOffsetPixels;

    /**
     * A currently selected marker 
     */
    private Marker marker;

    /**
     * Our custom view which is returned from either the InfoWindowAdapter.getInfoContents 
     * or InfoWindowAdapter.getInfoWindow
     */
    private View infoWindow;    

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

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

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

    /**
     * Must be called before we can route the touch events
     */
    public void init(GoogleMap map, int bottomOffsetPixels) {
        this.map = map;
        this.bottomOffsetPixels = bottomOffsetPixels;
    }

    /**
     * Best to be called from either the InfoWindowAdapter.getInfoContents 
     * or InfoWindowAdapter.getInfoWindow. 
     */
    public void setMarkerWithInfoWindow(Marker marker, View infoWindow) {
        this.marker = marker;
        this.infoWindow = infoWindow;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        boolean ret = false;
        // Make sure that the infoWindow is shown and we have all the needed references
        if (marker != null && marker.isInfoWindowShown() && map != null && infoWindow != null) {
            // Get a marker position on the screen
            Point point = map.getProjection().toScreenLocation(marker.getPosition());

            // Make a copy of the MotionEvent and adjust it's location
            // so it is relative to the infoWindow left top corner
            MotionEvent copyEv = MotionEvent.obtain(ev);
            copyEv.offsetLocation(
                -point.x + (infoWindow.getWidth() / 2), 
                -point.y + infoWindow.getHeight() + bottomOffsetPixels);

            // Dispatch the adjusted MotionEvent to the infoWindow
            ret = infoWindow.dispatchTouchEvent(copyEv);
        }
        // If the infoWindow consumed the touch event, then just return true.
        // Otherwise pass this event to the super class and return it's result
        return ret || super.dispatchTouchEvent(ev);
    }
}

所有这些都将使InfoView中的视图再次"活跃"——OnClickListeners将开始触发等等.

Second part:

但显示按钮按下状态或类似性质的内容要复杂得多.第一个问题是,(至少)我不能让InfoWindow显示正常按钮的按下状态.即使我按了很长一段时间,它也没有在屏幕上按下.我相信这是由MAP框架本身处理的事情,它可能确保不会在信息窗口中显示任何瞬时状态.但我可能错了,我没有试图找出这一点.

我做的是另一个令人讨厌的攻击-我在按钮上附加了一个OnTouchListener,当按钮被按下或释放时,我手动将其背景切换到两个自定义的抽屉-一个按钮处于正常状态,另一个处于按下状态.这不是很好,但很管用:).现在我可以在屏幕上看到按钮在正常状态和按下状态之间切换.

还有最后一个故障-如果你点击按钮太快,它不会显示按下状态-它只是保持在正常状态(尽管点击本身是触发的,所以按钮"工作").至少它在我的Galaxy Nexus上是这样显示的.所以我做的最后一件事是,我稍微延迟了按钮的按下状态.这也相当难看,我不确定它如何在一些较老的、速度较慢的设备上工作,但我怀疑即使是MAP框架本身也会做这样的事情.你可以自己试一下--当你点击整个InfoWindow时,它会保持一段时间的按下状态,比正常的按键要长一点(再一次--至少在我的手机上是这样).即使在最初的谷歌 map 应用程序上,它实际上也是这样工作的.

无论如何,我自己编写了一个自定义类来处理按钮状态更改和我提到的所有其他事情,所以下面是代码:

package com.circlegate.tt.cg.an.lib.map;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

import com.google.android.gms.maps.model.Marker;

public abstract class OnInfoWindowElemTouchListener implements OnTouchListener {
    private final View view;
    private final Drawable bgDrawableNormal;
    private final Drawable bgDrawablePressed;
    private final Handler handler = new Handler();

    private Marker marker;
    private boolean pressed = false;

    public OnInfoWindowElemTouchListener(View view, Drawable bgDrawableNormal, Drawable bgDrawablePressed) {
        this.view = view;
        this.bgDrawableNormal = bgDrawableNormal;
        this.bgDrawablePressed = bgDrawablePressed;
    }

    public void setMarker(Marker marker) {
        this.marker = marker;
    }

    @Override
    public boolean onTouch(View vv, MotionEvent event) {
        if (0 <= event.getX() && event.getX() <= view.getWidth() &&
            0 <= event.getY() && event.getY() <= view.getHeight())
        {
            switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN: startPress(); break;

            // We need to delay releasing of the view a little so it shows the pressed state on the screen
            case MotionEvent.ACTION_UP: handler.postDelayed(confirmClickRunnable, 150); break;

            case MotionEvent.ACTION_CANCEL: endPress(); break;
            default: break;
            }
        }
        else {
            // If the touch goes outside of the view's area
            // (like when moving finger out of the pressed button)
            // just release the press
            endPress();
        }
        return false;
    }

    private void startPress() {
        if (!pressed) {
            pressed = true;
            handler.removeCallbacks(confirmClickRunnable);
            view.setBackground(bgDrawablePressed);
            if (marker != null) 
                marker.showInfoWindow();
        }
    }

    private boolean endPress() {
        if (pressed) {
            this.pressed = false;
            handler.removeCallbacks(confirmClickRunnable);
            view.setBackground(bgDrawableNormal);
            if (marker != null) 
                marker.showInfoWindow();
            return true;
        }
        else
            return false;
    }

    private final Runnable confirmClickRunnable = new Runnable() {
        public void run() {
            if (endPress()) {
                onClickConfirmed(view, marker);
            }
        }
    };

    /**
     * This is called after a successful click 
     */
    protected abstract void onClickConfirmed(View v, Marker marker);
}

以下是我使用的自定义InfoWindow布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginRight="10dp" >

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:text="Title" />

        <TextView
            android:id="@+id/snippet"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="snippet" />

    </LinearLayout>

    <Button
        android:id="@+id/button" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>

测试活动布局文件(MapFragment位于MapWrapperLayout中):

<com.circlegate.tt.cg.an.lib.map.MapWrapperLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map_relative_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment" />

</com.circlegate.tt.cg.an.lib.map.MapWrapperLayout>

最后是一个测试活动的源代码,它将所有这些粘在一起:

package com.circlegate.testapp;

import com.circlegate.tt.cg.an.lib.map.MapWrapperLayout;
import com.circlegate.tt.cg.an.lib.map.OnInfoWindowElemTouchListener;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {    
    private ViewGroup infoWindow;
    private TextView infoTitle;
    private TextView infoSnippet;
    private Button infoButton;
    private OnInfoWindowElemTouchListener infoButtonListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
        final MapWrapperLayout mapWrapperLayout = (MapWrapperLayout)findViewById(R.id.map_relative_layout);
        final GoogleMap map = mapFragment.getMap();

        // MapWrapperLayout initialization
        // 39 - default marker height
        // 20 - offset between the default InfoWindow bottom edge and it's content bottom edge 
        mapWrapperLayout.init(map, getPixelsFromDp(this, 39 + 20)); 

        // We want to reuse the info window for all the markers, 
        // so let's create only one class member instance
        this.infoWindow = (ViewGroup)getLayoutInflater().inflate(R.layout.info_window, null);
        this.infoTitle = (TextView)infoWindow.findViewById(R.id.title);
        this.infoSnippet = (TextView)infoWindow.findViewById(R.id.snippet);
        this.infoButton = (Button)infoWindow.findViewById(R.id.button);

        // Setting custom OnTouchListener which deals with the pressed state
        // so it shows up 
        this.infoButtonListener = new OnInfoWindowElemTouchListener(infoButton,
                getResources().getDrawable(R.drawable.btn_default_normal_holo_light),
                getResources().getDrawable(R.drawable.btn_default_pressed_holo_light)) 
        {
            @Override
            protected void onClickConfirmed(View v, Marker marker) {
                // Here we can perform some action triggered after clicking the button
                Toast.makeText(MainActivity.this, marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
            }
        }; 
        this.infoButton.setOnTouchListener(infoButtonListener);


        map.setInfoWindowAdapter(new InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker marker) {
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {
                // Setting up the infoWindow with current's marker info
                infoTitle.setText(marker.getTitle());
                infoSnippet.setText(marker.getSnippet());
                infoButtonListener.setMarker(marker);

                // We must call this to set the current marker and infoWindow references
                // to the MapWrapperLayout
                mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
                return infoWindow;
            }
        });

        // Let's add a couple of markers
        map.addMarker(new MarkerOptions()
            .title("Prague")
            .snippet("Czech Republic")
            .position(new LatLng(50.08, 14.43)));

        map.addMarker(new MarkerOptions()
            .title("Paris")
            .snippet("France")
            .position(new LatLng(48.86,2.33)));

        map.addMarker(new MarkerOptions()
            .title("London")
            .snippet("United Kingdom")
            .position(new LatLng(51.51,-0.1)));
    }

    public static int getPixelsFromDp(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int)(dp * scale + 0.5f);
    }
}

就这样.到目前为止,我只在我的Galaxy Nexus(4.2.1)和Nexus 7(也是4.2.1)上进行了测试,有机会我会在姜饼手机上试用.到目前为止,我发现的一个限制是,您不能从屏幕上按钮所在的位置拖动 map ,也不能四处移动 map .它可能会以某种方式被克服,但就目前而言,我可以接受这一点.

我知道这是一个丑陋的黑客,但我只是没有找到更好的,我非常需要这个设计模式,这将是一个真正的理由回到 map v1框架(顺便说一句,我真的很想避免一个新的应用程序与碎片等).我只是不明白为什么谷歌不为开发者提供一些在InfoWindows上安装按钮的官方方式.这是一种非常常见的设计模式,而且这种模式甚至在官方的谷歌 map 应用程序中也有使用:).我理解为什么他们不能让你的视图在InfoWindows中"活"起来——这可能会降低移动和滚动 map 时的性能.但是应该有一些方法可以在不使用视图的情况下实现这种效果.

Android相关问答推荐

如何在cordova 中播放html5视频标签?

如何使禁用状态下的material 3按钮与启用状态下的 colored颜色 相同?

合成 colored颜色 的GSON反序列化

房间DB:UPSERT返回什么?

Jetpack Compose:如何将浮动操作按钮上方的子按钮居中对齐?

strings.xml中字符串数组中的占位符

找不到类MultipartBody;的序列化程序

当我想使用例如 material3 时,为什么我需要添加对 material 的依赖?底部导航?

Android 应用程序从 Android Studio 安装,但不是作为 .apk 在外部安装.抛出java.lang.UnsatisfiedLinkError

在段的中心绘制饼图(甜甜圈图)的图例

列语义在列中的第一个元素之后读取

在 Jetpack Compose 中包装内容

没有互联网连接时,Firebase Storage putFile() 永远不会完成

Jetpack Compose TextField 在输入新字符时不更新

Android Compose:LazyColumn 和 Column with verticalScroll 的区别

在开发过程中我应该把 mp4 文件放在哪里?

如何使用文件提供程序将视频从一个应用程序共享到另一个应用程序?

设备文件资源管理器-ROOM 数据库中的数据库文件夹为空

Android Studio (Kotlin):无法启动活动

compose :为什么以记住启动的列表触发方式与快照不同