很多App都需要点击某一个Button就会从底部弹出一个Dialog,就像微信的分享等
话不多说,直接上代码了
自定义一个方法
bottomDialog = new Dialog(this, R.style.BottomDialog);
//加载自己的布局
View contentView = LayoutInflater.from(this).inflate(R.layout.view_data_selete, null);
//自定义的布局的控件一定要用ContentView.findViewById,不然会报错
calendarView = contentView.findViewById(R.id.calendar);
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的parent需要设定parent="@style/Base.V7.Theme.AppCompat.Light.Dialog",同时将对话框所在window的标题去掉。android:windowBackground属性一定要设置成透明,否则自定义形状的对话框背景就是默认的白色了。
<style name="BottomDialog" parent="@style/Base.V7.Theme.AppCompat.Light.Dialog">
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
</style>
最后就是对话框显示时从底部进入,关闭时从底部滑出的动画样式:
tranlate_dialog_in.xml:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="300"
android:fromXDelta="0"
android:fromYDelta="100%"
android:toXDelta="0"
android:toYDelta="0">
</translate>
tranlate_dialog_out.xml:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="300"
android:fromXDelta="0"
android:fromYDelta="0"
android:toXDelta="0"
android:toYDelta="100%">
</translate>
原理就是修改对话框的内容布局contentView的参数,使它的宽度刚好等于屏幕的宽度,并且设置对话框所在Window的gravity属性为bottom,这样就搞定啦。
有不懂的小伙伴欢迎留言!!!