Android的對話方塊有兩種:PopupWindow和AlertDialog。它們的不同點在於:
AlertDialog的位置固定,而PopupWindow的位置可以隨意
AlertDialog是非阻塞線程的,而PopupWindow是阻塞線程的
PopupWindow的位置按照有無位移分,可以分為位移和無位移兩種;按照參照物的不同,可以分為相對於某個控制項(Anchor錨)和相對於父控制項。具體如下
showAsDropDown(View anchor):相對某個控制項的位置(正左下方),無位移
showAsDropDown(View anchor, int xoff, int yoff):相對某個控制項的位置,有位移
showAtLocation(View parent, int gravity, int x, int y):相對於父控制項的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以設定位移或無位移
不解釋之際上代碼
[java]
LayoutInflater inflater = (LayoutInflater) DeliveryActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.popup_sms, null);
LinearLayout popup_contact = (LinearLayout)view.findViewById(R.id.popup_contact);
LinearLayout popup_input = (LinearLayout)view.findViewById(R.id.popup_input);
popup_contact.setOnClickListener(DeliveryActivity.this);
popup_input.setOnClickListener(DeliveryActivity.this);
selectSMSPopup = new PopupWindow(view);
selectSMSPopup.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
selectSMSPopup.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
// 必須設定,否則獲得焦點後頁面上其他地方點擊無響應
selectSMSPopup.setBackgroundDrawable(new BitmapDrawable());
// 設定焦點,必須設定,否則listView無法響應
selectSMSPopup.setFocusable(true);
// 設定點擊其他地方 popupWindow消失
selectSMSPopup.setOutsideTouchable(true);
// 顯示在某個位置
selectSMSPopup.showAsDropDown(LinearLayout