最近希望用百度地图的PopupOverlay弹出自定义的View弹窗,但百度的API只支持Bitmap的弹窗
于是在网上搜索方法时看到了用DrawCache方法把View转成BitMap再显示,但只有ios的实现,我在这篇文章里说下Android的实现
源码的模版是百度地图API给出的2.0.0示例代码,下载见点击打开链接
主要对其中的自定义覆盖物(ItemizedOverlayDemo)模块进行了修改,使其实现自定义弹窗
首先加入一个将View转换为Bitmap的方法(参考自点击打开链接)
这一方法也解决了getDrawingCache为null的问题
public static Bitmap convertViewToBitmap(View view) {
view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
return bitmap;
}
然后新建一个自定义弹窗XML以供自定义时调用
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/popup_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/pop" >
<TextView
android:id="@+id/test_text"
android:gravity="center"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"
android:textColor="@android:color/black" />
</LinearLayout>
然后对OnTap模块进行修改,与Popupwindow的代码差不多
protected boolean onTap(int index) {
View popview = LayoutInflater.from(mContext).inflate(
R.layout.popup_view, null);// 获取要转换的View资源
TextView TestText = (TextView)popview.findViewById(R.id.test_text);
TestText.setText(mGeoList.get(index).getTitle());//将每个点的Title在弹窗中以文本形式显示出来
Bitmap popbitmap = convertViewToBitmap(popview);
pop.showPopup(popbitmap, mGeoList.get(index).getPoint(), 32);
// int latspan = this.getLatSpanE6();
// int lonspan = this.getLonSpanE6();
Toast.makeText(this.mContext, mGeoList.get(index).getTitle(),
Toast.LENGTH_SHORT).show();
super.onTap(index);
return false;
}
缺点:这一方法的缺点就是若有多个按钮无法分别识别,因为它已经变成一张图了
对于弹窗的点击事件可以通过设置onClickedPopup()完成
如果一定要实现多按钮区别操作的话,只能用PopupWindow了(我以前的博文也写过相关的,不知道会不会有帮助)
效果图: