需求
开发中经常会遇见从底部弹出的弹窗 , 如果你设置的Popupwindow是MATCH_PARENT的话 , 并在弹窗的布局中设置了背景 , 那么设置从底部弹出弹窗的时候 , 会出现整个阴影背景的弹出效果 , 这肯定不是UI妹妹想要的效果 , 如何解决呢
首先
创建弹窗
normalPopUpWindow = new NormalPopUpWindow(contentView,
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
normalPopUpWindow.setOutsideTouchable(true);
normalPopUpWindow.setBackgroundDrawable(new BitmapDrawable());
normalPopUpWindow
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
normalPopUpWindow.setOnDismissListener(() -> {
startbgAnimation(context, false);
});
normalPopUpWindow.setAnimationStyle(R.style.pop_animation_enter);
normalPopUpWindow.showAtLocation(context.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
startbgAnimation(context, true);
注意
弹窗的布局文件根布局为WRAP_CONTENT , 有多大的地占多大的坑就行
然后
在弹窗弹出的同时 , 对整个手机的窗口进行颜色渐变
private static void startbgAnimation(Activity context, boolean isEnter) {
float start;
float end;
if (isEnter) {
start = 1f;
end = 0.7f;
} else {
start = 0.7f;
end = 1f;
}
WindowManager.LayoutParams wlp = context.getWindow().getAttributes();
ValueAnimator valueAnimator = ValueAnimator.ofFloat(start, end);
valueAnimator.setDuration(400);
valueAnimator.setRepeatCount(0);
valueAnimator.addUpdateListener(animation -> {
wlp.alpha = (float) animation.getAnimatedValue();
context.getWindow().setAttributes(wlp);
});
valueAnimator.start();
}
注意
弹窗弹出的同时 , 开始窗体的颜色渐变 , 为popupwindow注册setOnDismissListener监听, 但监听到popupwindow消失时 , 记得把窗体的颜色还原 .
值得注意的是 , 通过这个方法可以解决 : 如果是布局中设置根布局都设置MATCH_PARENT的话 , 并对根布局进行设置阴影 , 会出现弹出的popupwindow后 , 电池栏的颜色的冲突 , 而使用我们这个方法的话 , 既不用设置布局的背景阴影 , 又可以使整个popupwindow的背景和电池栏的颜色一致 , 还可以使由下往上的弹窗动画更美观 .
弹窗动画
styles.xml
<style name="pop_animation_enter" parent="android:Animation">
<item name="android:windowEnterAnimation">@anim/enter_top</item>
<item name="android:windowExitAnimation">@anim/exit_bottom</item>
</style>
在res/anim下 , 如果没有anim文件夹 , 创建一个anim文件夹
添加enter_top.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:interpolator/accelerate_decelerate"
>
<translate
android:duration="400"
android:fromYDelta="100%p"
android:toYDelta="0" />
<alpha
android:duration="400"
android:fromAlpha="0.5"
android:toAlpha="1.0" />
</set>
添加exit_bottom.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:interpolator/accelerate_decelerate">
<alpha
android:duration="400"
android:fromAlpha="1.0"
android:toAlpha="0.5" />
<translate
android:duration="400"
android:fromYDelta="0"
android:toYDelta="100%p" />
</set>