PopuwWindow使用細節(觸摸外部不消失及返回鍵監聽,動畫使用)

PopuwWindow使用非常常見,這裏簡單介紹其使用,
1、怎樣使其點擊空白處不消失,
2、怎樣監聽返回鍵,
3、怎樣使用透明度,
4、動畫使用;
先貼代碼:

1、顯示及空白點擊問題

View delete_view = LayoutInflater.from(this).inflate(R.layout.layout_delete,null);
ImageView iv_cancel = (ImageView) delete_view.findViewById(R.id.iv_delete_cancel);//右上角錯號
Button btn_delete = (Button) delete_view.findViewById(R.id.btn_delete);//刪除按鈕
TextView tv_delete_hint = (TextView) delete_view.findViewById(R.id.tv_delete_hint);//刪除提示語
tv_delete_hint.setText("同步報告成功");
btn_delete.setText("確定");
popupWindow = new PopupWindow(delete_view,ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,true);//使用Match_parent,才能使得點擊空白處不消失,否則無效;
popupWindow.setTouchable(true);
popupWindow.setTouchable(true);
//下面兩個屬性必須設置,才能使得點擊空白處有效
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setOutsideTouchable(false);
popupWindow.setContentView(delete_view);

//整個屏幕居中顯示                                        popupWindow.showAtLocation(getWindow().getDecorView().getRootView(), Gravity.CENTER,0,0);

2、設置透明度

//設置背景爲半透明
WindowManager.LayoutParams params = getWindow().getAttributes();
params.alpha = 0.8f;//透明度爲0.8
getWindow().setAttributes(params);
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
   @Override
   public void onDismiss() {
       WindowManager.LayoutParams params = getWindow().getAttributes();
       params.alpha = 1f;
       getWindow().setAttributes(params);
   }
});

3、返回鍵監聽

popupWindowView.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                //do something...
                return true;
            }
        });

4、PopuwWindow也可以使用一些動畫效果

//顯示
    <?xml version="1.0" encoding="utf-8"?>  
    <set xmlns:android="http://schemas.android.com/apk/res/android">    
        <translate    
            android:fromXDelta="0"    
            android:toXDelta="0"    
            android:fromYDelta="120"    
            android:toYDelta="0"    
            android:duration="500" />    
    </set>  
//消失
<?xml version="1.0" encoding="utf-8"?>  
<set xmlns:android="http://schemas.android.com/apk/res/android">    
    <translate    
        android:fromXDelta="0"    
        android:toXDelta="0"    
        android:fromYDelta="0"    
        android:toYDelta="120"    
        android:duration="500" />    
</set> 

在styles.xml中添加樣式

    <style name="popwin_anim_style">  
         <item name="android:windowEnterAnimation">@anim/menushow</item>  
         <item name="android:windowExitAnimation">@anim/menuhide</item>  
    </style>  

最後在代碼中通過setAnimationStyle(int id)方法添加動畫,比較簡單,大家可以嘗試使用一下。

總結:在項目中這些使用能解決大部分的彈窗問題,不建議使用alertDialog,一是太醜,二是樣式改變比較麻煩,三是位置只可以放在中間;popuwWindow位置可以隨意放,完美的解決了這些問題;假如本文對大家有幫助,不要忘記了點個贊喲,小編會更加努力產文

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章