溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

PopupWindow詳解

發(fā)布時(shí)間:2020-06-29 11:36:32 來(lái)源:網(wǎng)絡(luò) 閱讀:392 作者:joyy001 欄目:移動(dòng)開(kāi)發(fā)

Android的對(duì)話框有兩種:PopupWindow和AlertDialog。它們的不同點(diǎn)在于:

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


下面介紹PopupWindow的用法:

PopupWindow的位置按照有無(wú)偏移分,可以分為偏移和無(wú)偏移兩種;按照參照物的不同,可以分為相對(duì)于某個(gè)控件和相對(duì)于父控件

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


具體代碼:

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

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

}


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

當(dāng)設(shè)置為popuWindow.setFocusable(true);的時(shí)候,加上下面兩行設(shè)置背景代碼,點(diǎn)擊外面和Back鍵才會(huì)消失

mPopupWindow.setOutsideTouchable(true):設(shè)置顯示PopuWindow之后在外面點(diǎn)擊是否有效。如果為false的話,那么點(diǎn)擊PopuWindow外面并不會(huì)關(guān)閉PopuWindow。當(dāng)然這里很明顯只能在Touchable下才能使用。

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


向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI