PopupWindow詳解

Android的對話框有兩種:PopupWindow和AlertDialog。它們的不同點在於:

AlertDialog的位置固定,而PopupWindow的位置可以隨意
AlertDialog是非阻塞線程的,而PopupWindow是阻塞線程的


下面介紹PopupWindow的用法:

PopupWindow的位置按照有無偏移分,可以分爲偏移和無偏移兩種;按照參照物的不同,可以分爲相對於某個控件和相對於父控件

showAsDropDown(View anchor):相對某個控件的位置(正左下方),無偏移
showAsDropDown(View anchor, int xoff, int yoff):相對某個控件的位置,有偏移
showAtLocation(View parent, int gravity, int x, int y):相對於父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以設置偏移或無偏移


具體代碼:

private void showPopupWindow(View v) {  //v爲父控件
View inflate = LayoutInflater.from(getActivity()).inflate(
				R.layout.pop_del, null); //定義一個佈局
		mPopupWindow = new PopupWindow(inflate, 140, 40); //傳入佈局,及Popupwindow的寬高
		//如果要實現點擊PopupWindow之外的區域,關閉PopupWindow,要增加下面這3個屬性
		mPopupWindow.setFocusable(true);
		mPopupWindow.setOutsideTouchable(true);
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		//PopupWindow彈出及關閉動畫
		mPopupWindow.setAnimationStyle(R.style.PopAnim);
		int[] location = new int[2];
		v.getLocationOnScreen(location); //獲取父控件在屏幕上的位置座標
		//將Popupwindow顯示在父控件的左邊,location[0]爲父控件的橫座標,location[1]爲父控件的縱座標
		mPopupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0]
				- mPopupWindow.getWidth(), location[1]);
		//設置佈局的點擊監聽,點擊PopupWindow之外的區域,關閉PopupWindow	
		inflate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
			if(mPopupWindow != null){
				mPopupWindow.dismiss();
				mPopupWindow = null;
			}
			}
		});

}


mPopupWindow.setFocusable(false):說明PopuWindow不能獲得焦點,即使設置設置了背景不爲空也不能點擊外面消失,只能由dismiss()消失,但是外面的View的事件還是可以觸發,back鍵也可以順利dismiss掉。

當設置爲popuWindow.setFocusable(true);的時候,加上下面兩行設置背景代碼,點擊外面和Back鍵纔會消失

mPopupWindow.setOutsideTouchable(true):設置顯示PopuWindow之後在外面點擊是否有效。如果爲false的話,那麼點擊PopuWindow外面並不會關閉PopuWindow。當然這裏很明顯只能在Touchable下才能使用。

要讓PopUpWindow dimiss(即點擊PopuWindow之外的地方此或者back鍵PopuWindow會消失),PopUpWindow的背景不能爲空。必須在popuWindow.showAsDropDown(v);或者其它的顯示PopuWindow方法之前設置它的背景不爲空:mPopupWindow.setBackgroundDrawable(new BitmapDrawable());


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