效果圖如下:
PopupWindow 是一個可以顯示在當前 Activity 之上的浮動容器,PopupWindow
彈出的位置是能夠改變的,按照有無偏移量,可以分爲無偏移和有偏移兩種;按照參照對象的不同又可以分爲兩種:相對某個控件(Anchor 錨點)的位置和在父容器內部的相對位置。
PopupWindow 的實現代碼如下:
創建 PopupWindow
LayoutInflater mLayoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
View contentView = mLayoutInflater.inflate(R.layout.pop, null)// R.layout.pop爲 PopupWindow 的佈局文件
PopupWindow pop = new PopupWindow(contentView, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
pop.setBackgroundDrawable(new BitmapDrawable()); // 指定 PopupWindow 的背景
pop.setFocusable(true); // 設定 PopupWindow 取的焦點,創建出來的 PopupWindow 默認無焦點
顯示
PopupWindow
// 相對某個控件的位置(正左下方),無偏移
pop.showAsDropDown(View anchor)
// 相對某個控件的位置,有偏移,xoff 爲 X 軸的偏移量,yoff 爲 Y 軸的偏移量
pop.showAsDropDown(View anchor, int xoff, int yoff)
// 在父容器的什麼位置,gravity 爲相對位置,如:正中央 Gravity.CENTER、下方 Gravity.BOTTOM、Gravity.RIGHT|Gravity.BOTTOM 右下方等,後面兩個參數爲 x/y 軸的偏移量。
pop.showAtLocation(View parent, int gravity, int x, int y)
關閉
PopupWindowpop.dismiss()