百度地圖自定義彈窗(PopupOverlay)Android篇

最近希望用百度地圖的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了(我以前的博文也寫過相關的,不知道會不會有幫助)

 

效果圖:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章