栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

Android实现底部对话框BottomDialog弹出实例代码

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android实现底部对话框BottomDialog弹出实例代码

最近项目上需要实现一个底部对话框,要实现这样的功能其实很简单,先看代码:

private void show1() {
 Dialog bottomDialog = new Dialog(this, R.style.BottomDialog);
 View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_content_normal, null);
 bottomDialog.setContentView(contentView);
 ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
 layoutParams.width = getResources().getDisplayMetrics().widthPixels;
 contentView.setLayoutParams(layoutParams);
 bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
 bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
 bottomDialog.show();
}

对话框的样式style:


 true
 @android:color/transparent

在对话框中的按钮需要MD风格的波纹效果的话,对话框的style的parent需要设定parent="@style/base.V7.Theme.AppCompat.Light.Dialog",否则没有效果。同时将对话框所在window的标题去掉。android:windowBackground属性一定要设置成透明,否则自定义形状的对话框背景就是默认的白色了。如果不设置为透明,比如我们通常要设置的圆角对话框就没有效果。

对话框显示时从底部进入,关闭时从底部滑出。动画样式:


 @anim/translate_dialog_in
 @anim/translate_dialog_out

tranlate_dialog_in.xml:



tranlate_dialog_out.xml:



实现底部对话框的原理就是修改对话框的内容布局contentView的参数,使它的宽度刚好等于屏幕的宽度,并且设置对话框所在Window的gravity属性为bottom。

需要注意的是,上面代码中需要在调用contentView.getLayoutParams()需要在setContentView方法后,否则获取到的LayoutParams为null,当然也可以自己new一个LayoutParams设置给contentView。


如果是要实现底部圆角对话框,原理也相似,只需要给contentView添加一个圆角的背景shape,并减小contentView的宽度给左右两边留一定的距离,同时给底部设置边距。

private void show2() {
 Dialog bottomDialog = new Dialog(this, R.style.BottomDialog);
 View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_content_circle, null);
 bottomDialog.setContentView(contentView);
 ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
 params.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(this, 16f);
 params.bottomMargin = DensityUtil.dp2px(this, 8f);
 contentView.setLayoutParams(params);
 bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
 bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
 bottomDialog.show();
}

 源码:BottomDialog_jb51.rar

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/159314.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号