PopupWindow用法

PopupWindow用法


參考:http://blog.csdn.net/hlyjunhe/article/details/6572159   
http://www.cnblogs.com/noTice520/archive/2011/08/16/2140356.html
http://www.2cto.com/kf/201108/100378.html
http://www.cnblogs.com/noTice520/archive/2011/02/15/1955541.html

 
使用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之外的地方此或者backPopuWindow會消失);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爲佈局文件

總結:

1PopupWindowview佈局,通過LayoutInflator獲取佈局的view.:

LayoutInflater inflater =(LayoutInflater)            

this.anchor.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View textEntryView =  inflater.inflate(R.layout.paopao_alert_dialognull);

       

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;

}

});


發佈了18 篇原創文章 · 獲贊 0 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章