介绍PopupWindow组件的属性和使用
- PopupWindow概述
Android的对话框有两种:PopupWindow AlertDialog.他们的不同点在于AlertDialog的位置固定,而PopupWindow的位置可以随意
PopupWindow的位置按照有无偏移,可以分为偏移和无偏移两种
按照参照物的不同,可以分为相对于某个控件(Anchor锚)和相对于父控件
- PopupWindow使用
想学PopupWindow,咱们先来看一下PopupWindow的效果,看下图:
public PopupWindow(View contentView) {
this(contentView, 0, 0);
}
public PopupWindow(View contentView, int width, int height) {
this(contentView, width, height, false);
}
public PopupWindow(View contentView, int width, int height, boolean focusable) {
......
}
所以,一般使用方法2创建:
View inflate = LayoutInflater.from(this).inflate(R.layout.pop, null, false);
final PopupWindow popupWindow = new PopupWindow(inflate, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
popupWindow.showAsDropDown(mBtn2,0,0);
PopupWindow没有默认布局,它不会像AlertDialog那样只setTitle,就能弹出来一个框。
创建PopupWindow(三要素)
-
创建PopupWindow注意点
首要注意:看这几个构造函数,但要生成一个PopupWindow最基本的三个条件是一定要设置的:View contentView,int width, int height ;少任意一个就不可能弹出来PopupWindow!!!! -
显示PopupWindow 区别
关闭PopupWindow在点击范围外
//必须先设置背景
popupWindow.setBackgroundDrawable(null);
popupWindow.setOutsideTouchable(true);
自定义PopupWindow实现全屏阴影
全屏阴影思路
// 修改背景透明度
public void backgroundAlpha(float bgAlpha) {
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = bgAlpha; //0.0-1.0 从完全透明 到 不透明
getWindow().setAttributes(lp);
}
View root = LayoutInflater.from(this).inflate(R.layout.pop_view, null);
PopupWindow popupWindow = new PopupWindow(root, 200, 200);
// 设置点击外部 消失popwindow
popupWindow.setBackgroundDrawable(new ColorDrawable());
popupWindow.setOutsideTouchable(true);
// 改变为半透明
backgroundAlpha(0.5f);
popupWindow.setAnimationStyle(R.style.pop_animation);
popupWindow.showAtLocation(mContent, Gravity.CENTER,0,0);
PopupWindow进入出动画设置
动画style 创建
popupWindow.setAnimationStyle(R.style.PopAnimation);
<style name="PopAnimation" parent="@android:style/Animation">
<item name="android:windowExitAnimation">@anim/anim_eixt</item>
<item name="android:windowEnterAnimation">@anim/anim_enter</item>
</style>
anim_exit.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1500"
>
<translate
android:fromXDelta="0"
android:toXDelta="100%p"
android:fromYDelta="0"
android:toYDelta="100%p"
/>
<alpha
android:fromAlpha="1.0"
android:toAlpha="0"
/>
</set>
anim_enter.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1500"
>
<translate
android:fromXDelta="100%p"
android:toXDelta="0"
android:fromYDelta="100%p"
android:toYDelta="0"
/>
<alpha
android:fromAlpha="0"
android:toAlpha="1.0"
/>
</set>