android 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.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;

}

});


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM