PopupWindow
兩個方法:showAtLocation(相對於組件parent屏幕)和showAsDropDown(相對於組件)
showAtLocation:
public void showAtLocation(View parent, int gravity, int x, int y)parent可以爲Activity中的任意一個View(最終的效果一樣),會通過這個View找到其父Window,也就是Activity的Window。
gravity,默認爲Gravity.NO_GRAVITY,等效於Gravity.LEFT | Gravity.TOP
x, y,邊距。這裏的x,y表示距離Window邊緣的距離,方向由Gravity決定。例如:設置了Gravity.TOP,則y表示與Window上邊緣的距離;而如果設置了Gravity.BOTTOM,則y表示與下邊緣的距離。
如果彈窗位置超出了Window的範圍,會自動處理使其處於Window中
相對於屏幕(左上角0,0),窗位置超出了Window的範圍,會自動處理使其處於Window中,顯示範圍是頂部和底部
注意使用的時候,如果設置Gravity.TOP,則要計算狀態欄的高度
注意:在Android7.0此方法不生效,如果想在屏幕中間位置,解決辦法在屏幕中間畫根線,然後用showAsDropDown相對於這根線做偏移
public void showAsDropDown(View anchor, int xoff, int yoff)
彈窗會顯示在anchor控件的正下方。
如果指定了xoff和yoff,則會在原有位置向右偏移xoff,向下偏移yoff。
如果指定gravity爲Gravity.RIGHT,則彈窗和控件右對齊;否則左對齊。注意,計算右對齊時使用了- PopupWindow的寬度,如果指定的寬度不是固定值,則計算會失效(可以從源碼中看出來)。
如果彈窗位置超出了Window的範圍,會自動處理使其處於Window中。
如果anchor可以滾動,則滾動過程中,PopupWindow可以自動更新位置,跟隨anchor控件。
相對於組件(左下角 0,屏幕高度)
總結:showAtLocation 和 showAsDropDown 主要區別於顯示位置相對於屏幕還是組件
dialog
附上代碼,關鍵
lp.y = high; // 新位置Y座標
dialog = new Dialog(context, R.style.DialogMore); dialog.setContentView(R.layout.toast_dialog_item); tv = (TextView) dialog.findViewById(R.id.tv_content); tv.setText(contents); //點擊dialog旁邊空白不關閉 dialog.setCanceledOnTouchOutside(false); //點擊回退按鈕不關閉 // dialog.setCancelable(false); Window window = dialog.getWindow(); window.setGravity(Gravity.TOP); // 非常重要:設置對話框彈出的位置 window.setWindowAnimations(R.style.DialogMore); //設置窗口彈出動畫 // 設置dialog對齊兩邊 WindowManager windowManager = ((Activity) mContext).getWindowManager(); Display display = windowManager.getDefaultDisplay(); WindowManager.LayoutParams lp = dialog.getWindow().getAttributes(); lp.width = (int) (display.getWidth() * 1.0); //設置寬度 lp.y = high; // 新位置Y座標
lp.x = 0; // 新位置X座標dialog.getWindow().setAttributes(lp); dialog.show();