Android底部弹窗
再一次需求中,使用到了底部弹窗,这里就给大家总结一下,我用到的主要有两种
- 基于Dialog实现
- 基于PopupWindow实现
Dialog方式
老规矩,直接上代码:
Dialog dialog = new Dialog(getContext(), R.style.BottomDialogTheme);
//获得dialog的window窗口
Window window = dialog.getWindow();
//设置dialog在屏幕底部
window.setGravity(Gravity.BOTTOM);
//设置dialog弹出时的动画效果,从屏幕底部向上弹出
window.setWindowAnimations(R.style.PopupAnimation);
window.getDecorView().setPadding(0, 0, 0, 0);
//获得window窗口的属性
android.view.WindowManager.LayoutParams lp = window.getAttributes();
//设置窗口宽度为充满全屏
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
//设置窗口高度为包裹内容
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
//将设置好的属性set回去
window.setAttributes(lp);
//将自定义布局加载到dialog上
dialog.setContentView(itemView);
dialog.show();
相关资源
Dialog的相关主题风格
<style name="BottomDialogTheme" parent="android:Theme.Dialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
</style>
Dialog弹出风格
<style name="PopupAnimation" parent="android:Animation">
<item name="android:windowEnterAnimation">@anim/up_in</item>
<item name="android:windowExitAnimation">@anim/down_out</item>
</style>
相关动画
up_in
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:fromYDelta="80%p"
android:toYDelta="0"
android:duration="100"
/>
</set>
down_out
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:fromYDelta="0"
android:toYDelta="80%p"
android:duration="400"
/>
</set>
使用
直接使用下面代码
View itemView = View.inflate(getContext(), R.layout.poup_mark_msg, null);
讲poup_mark_msg.xml替换成自己的需要的布局即可。
PopupWindow方式
与Dialog方式使用类似,代码如下:
View view = this.getLayoutInflater()
.inflate(R.layout.poup_mark_msg, null);
popupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
popupWindow.setFocusable(true);
popupWindow.setOutsideTouchable(true);
popupWindow.setBackgroundDrawable(new ColorDrawable(0));
popupWindow.setAnimationStyle(R.style.PopupAnimation);
popupWindow.showAtLocation(main, Gravity.BOTTOM, 0, 0);
//透明度变暗
backgroundAlpha(0.7f);
//添加popupwindow消失监听
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
//还原透明度
backgroundAlpha(1.0f);
}
});
一般我们都会为了突出弹窗,讲其他部分添加一层阴影,这里实现起来也很简单直接监听popupWindow的现实和消失修改透明度即可 。
关键方法如下:
/**
* 设置添加屏幕的背景透明度
*
* @param bgAlpha
*/
public void backgroundAlpha(float bgAlpha) {
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = bgAlpha; //0.0-1.0
getWindow().setAttributes(lp);
}
使用
同Dialog的使用方式