可能你們常常用彈出對話框也就是AlertDialog來進項一些操做, html
今天咱們用另一種彈窗效果來完成 java
使用的到類PopupWindow android
官方說明: app
java.lang.Object ide
↳
android.widget.PopupWindow 函數
A popup window that can be used to display an arbitrary view. The popup window is a floating container that appears on top of the current activity. 佈局
一個 彈出窗口能夠被使用去展現一個任意的視圖,這個彈出窗口是一個出如今當前activity上的懸浮的容器, 動畫
部分方法說明: spa
一、顯示的方法: code
showAtLocation()顯示在指定位置
showAsDropDown()顯示在一個參照物View的周圍
簡單使用demo
一、建立一個字段
/*彈出的懸浮窗體*/ private PopupWindow popupWindow;
//將關閉popupWindow窗口的操做封裝爲一個函數
dismissPopupWindow(popupWindow); View contentView = View.inflate(getApplicationContext(), R.layout.popup_app_item, null); /*-2表明包裹內容 -1表明填充父窗體*/ popupWindow = new PopupWindow(contentView, -2, -2); popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); int[] location = new int[2]; view.getLocationInWindow(location); /*或操做等於加操做*/ /*參數一、父窗體 參數二、佈局控制 參數三、距離左邊距離 參數四、距離頂部距離*/ int dip = 60; int px = DensityUtil.dip2px(getApplicationContext(), dip); popupWindow.showAtLocation(parent, Gravity.LEFT | Gravity.TOP, px, location[1]); /*popopWindow要求動畫效果的播放必需要求窗體有背景顏色*/ /*彈出動畫*/ ScaleAnimation scaleAnimation = new ScaleAnimation(0.3f, 1.0f, 0.3f, 1.0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.5f); scaleAnimation.setDuration(500); /*透明度*/ AlphaAnimation alphaAnimation = new AlphaAnimation(0.5f, 1.0f); alphaAnimation.setDuration(500); AnimationSet animationSet = new AnimationSet(false); animationSet.addAnimation(scaleAnimation); animationSet.addAnimation(alphaAnimation); contentView.startAnimation(animationSet);
關閉窗體的函數
private void dismissPopupWindow(PopupWindow popupWindow) { /*彈出窗體*/ if (popupWindow != null && popupWindow.isShowing()) { popupWindow.dismiss(); popupWindow = null; } }
注意事項:
@Override protected void onDestroy() { dismissPopupWindow(popupWindow); super.onDestroy(); }
在destroy方法中要將其關閉銷燬,不然會報錯,由於其依賴於父Activity的存在而存在,當activity銷燬前不將其銷燬,就會產生錯誤