android showAsDropDown的用法屬性介紹,showasdropdown
使用PopupWindow可實現快顯視窗效果,,其實和AlertDialog一樣,也是一種對話方塊,兩者也經常混用,但是也各有特點。下面就看看使用方法。
首先初始化一個PopupWindow,指定視窗大小參數。
PopupWindow mPop = new PopupWindow(getLayoutInflater().inflate(R.layout.window, null),
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
也可以分開寫:
LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
//自訂布局
ViewGroup menuView = (ViewGroup) mLayoutInflater.inflate(
R.layout.window, null, true);
PopupWindow mPop = new PopupWindow(menuView, LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, true);
當然也可以手動設定PopupWindow大小。
mPop.setContentView(menuView );//設定包含視圖
mPop.setWidth(int )
mPop.setHeight(int )//設定彈出框大小
設定進場動畫:
mPop.setAnimationStyle(R.style.AnimationPreview);//設定動畫樣式
mPop.setOutsideTouchable(true);//這裡設定顯示PopuWindow之後在外面點擊是否有效。如果為false的話,那麼點擊PopuWindow外面並不會關閉PopuWindow。當然這裡很明顯只能在Touchable下才能使用。
當有mPop.setFocusable(false);的時候,說明PopuWindow不能獲得焦點,即使設定設定了背景不為空白也不能點擊外面消失,只能由dismiss()消失,但是外面的View的事件還是可以觸發,back鍵也可以順利dismiss掉。當設定為popuWindow.setFocusable(true);的時候,加上下面兩行設定背景代碼,點擊外面和Back鍵才會消失。
mPop.setFocusable(true);
需要順利讓PopUpWindow dimiss(即點擊PopuWindow之外的地方此或者back鍵PopuWindow會消失);PopUpWindow的背景不可為空。必須在popuWindow.showAsDropDown(v);或者其它的顯示PopuWindow方法之前設定它的背景不為空白:
mPop.setBackgroundDrawable(new ColorDrawable(0));
mPop.showAsDropDown(anchor, 0, 0);//設定顯示PopupWindow的位置位於View的左下方,x,y表示座標位移量
mPop.showAtLocation(findViewById(R.id.parent), Gravity.LEFT, 0, -90);(以某個View為參考),表示快顯視窗以parent組件為參考,位於左側,位移-90。
mPop.setOnDismissListenerd(new PopupWindow.OnDismissListener(){})//設定視窗消失事件
註:window.xml為布局檔案
總結:
1、為PopupWindow的view布局,通過LayoutInflator擷取布局的view.如:
LayoutInflater inflater =(LayoutInflater)
this.anchor.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View textEntryView = inflater.inflate(R.layout.paopao_alert_dialog, null);
2、顯示位置,可以有很多方式設定顯示方式
pop.showAtLocation(findViewById(R.id.ll2), Gravity.LEFT, 0, -90);
或者
pop.showAsDropDown(View anchor, int xoff, int yoff)
3、進出場動畫
pop.setAnimationStyle(R.style.PopupAnimation);
4、點擊PopupWindow地區外部,PopupWindow消失
this.window = new PopupWindow(anchor.getContext());
this.window.setTouchInterceptor(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() ==MotionEvent.ACTION_OUTSIDE) {
BetterPopupWindow.this.window.dismiss();
return true;
}
return false;
}
});