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位置可以随意放,完美的解决了这些问题;假如本文对大家有帮助,不要忘记了点个赞哟,小编会更加努力产文。