點擊這裡下載原始碼
Android中,使用手指觸摸,不能像電腦一樣有滑鼠左鍵和右鍵,所以會有一個PopupWindow來代替滑鼠右鍵。當使用者點擊的時候出現一個彈出的視窗與使用者交流資訊。好了,現在就開始介紹PopupWindow的用法。
首先聲明一個PopupWindow的對象
PopupWindow pop=null;
初始化pop
pop=new PopupWindow(v,ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
第一個參數是要在PopupWindow中顯示的的View,第二個參數是PopupWindow的寬,我設定的是與其父視窗一樣寬,第三個參數是PopupWindow的高度,我設定的是包含它裡面的類容。
我們需要在PopupWindow中設定什麼樣的類容根據需要,我設定的是幾個Button,從xml檔案中解析出來的
LayoutInflater l=LayoutInflater.from(this);
View v=l.inflate(R.layout.popup, null);
當使用者點擊按鈕的時候就讓PopupWindow顯示出來
@Override
public void onClick(View v) {
pop.showAsDropDown(button);
}
這時候PopupWindow就顯示在指定
showAsDropDown(View anchor)
anchor的左下方。
當我們不需要PopupWindow的時候調用
pop.dismiss();
另外PopupWindow顯示的時候可以用showAtLocation()方法
void android.widget.PopupWindow.showAtLocation(View parent, int gravity, int x, int y)
parent a parent view to get the
android.view.View.getWindowToken()
token from
gravity the gravity which controls the placement of the popup window
x the popup's x location offset
y the popup's y location offset
第一個參數是要將PopupWindow放到的View,第二個參數是位置,第三第四是位移值
pop.showAtLocation(WorkPopUpTestActivity.this.ll, Gravity.BOTTOM, 0, 0);
如果是這樣的話,就將PopupWindow放到了View的左下角。
最後注意:只有當View載入完成之後才能顯示PopupWindow,如果View沒有載入完成就載入的話會不成功。
判斷View是否載入完成可以判斷其寬度是否為為其0,若否,則載入完成。然後我們再載入PopupWindow。這裡可以用Handler來實現。
@Overridepublic void run() {// TODO Auto-generated method stubboolean b=true;while(b){try {Thread.sleep(5);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}if(ll!=null){if(ll.getWidth()!=0){hand.sendEmptyMessage(0);b=false;}}}}
如果載入完成就發送訊息。在Handler的handleMessage中處理訊息。代碼如下
Handler hand=new Handler(){@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.handleMessage(msg);pop.showAtLocation(WorkPopUpTestActivity.this.ll, Gravity.BOTTOM, 0, 0);}};
在handleMessage中顯示PopupWindow。