Android常用代码-底部弹出PopupWindow

  1. 1. 关键代码
  2. 2. 动画文件
  3. 3. 样式文件
  4. 4. 使用示例

关键代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* 显示自定义底部弹出PopupWindow
*
* @param parent 传根布局就好了
* @param contentView PopupWindow内容
* @param bgColor 背景颜色(窗体变暗效果)
* @param focusable 是否点击空白区域取消(非全屏时可以)和返回键关闭
* @param fullScreen 是否全屏
* @param onDismissListener 取消监听
*/
public void showBottomPopupWindow(View parent, View contentView, int bgColor, boolean focusable, boolean fullScreen, PopupWindow.OnDismissListener onDismissListener) {
hideBottomDialog();
AutoUtils.auto(contentView);
popupWindow = new PopupWindow(ViewGroup.LayoutParams.MATCH_PARENT, fullScreen ? ViewGroup.LayoutParams.MATCH_PARENT : ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.setContentView(contentView);
// 设置弹出窗体可点击
popupWindow.setFocusable(focusable);
// 设置弹出窗体的背景
popupWindow.setBackgroundDrawable(new ColorDrawable(bgColor));
if (onDismissListener != null) {
popupWindow.setOnDismissListener(onDismissListener);
}
//设置弹出窗体显示时的动画,从底部向上弹出
popupWindow.setAnimationStyle(R.style.ZzAnimationDialog);
popupWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
}
/**
* 隐藏自定义底部弹出PopupWindow
*/
public void hideBottomDialog() {
if (popupWindow != null) {
popupWindow.dismiss();
popupWindow = null;
}
}

动画文件

  • bottom_dialog_enter.xml
1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/decelerate_interpolator">
<translate
android:duration="400"
android:fromYDelta="100%p"
android:toYDelta="0" />
<alpha
android:duration="400"
android:fromAlpha="0.0"
android:toAlpha="1.0" />
</set>
  • bottom_dialog_exit.xml
1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator">
<translate
android:duration="300"
android:fromYDelta="0"
android:toYDelta="100%p" />
<alpha
android:duration="300"
android:fromAlpha="1.0"
android:toAlpha="0.0" />
</set>

样式文件

1
2
3
4
<style name="ZzAnimationDialog">
<item name="android:windowEnterAnimation">@anim/bottom_dialog_enter</item>
<item name="android:windowExitAnimation">@anim/bottom_dialog_exit</item>
</style>

使用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
View root = LayoutInflater.from(mContext).inflate(R.layout.dialog_login_more, null);
ImageView ivClose = (ImageView) root.findViewById(R.id.iv_close);
ivClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hideBottomDialog();
}
});
showBottomPopupWindow(findViewById(R.id.root), root, Color.TRANSPARENT, true, false, new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {

}
});