最近項目上需要實現(xiàn)一個底部對話框,要實現(xiàn)這樣的功能其實很簡單,先看代碼:
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:
<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>
在對話框中的按鈕需要MD風格的波紋效果的話拉岁,對話框的style
的parent
需要設定parent="@style/Base.V7.Theme.AppCompat.Light.Dialog"
弟灼,否則沒有效果嗽上。同時將對話框所在window
的標題去掉。android:windowBackground
屬性一定要設置成透明伊约,否則自定義形狀的對話框背景就是默認的白色了姚淆。如果不設置為透明,比如我們通常要設置的圓角對話框就沒有效果屡律。
對話框顯示時從底部進入腌逢,關閉時從底部滑出。動畫樣式:
<style name="BottomDialog.Animation" parent="Animation.AppCompat.Dialog">
<item name="android:windowEnterAnimation">@anim/translate_dialog_in</item>
<item name="android:windowExitAnimation">@anim/translate_dialog_out</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>
實現(xiàn)底部對話框的原理就是修改對話框的內容布局contentView
的參數(shù)超埋,使它的寬度剛好等于屏幕的寬度搏讶,并且設置對話框所在Window
的gravity
屬性為bottom
佳鳖。
需要注意的是,上面代碼中需要在調用contentView.getLayoutParams()
需要在setContentView
方法后媒惕,否則獲取到的LayoutParams
為null
系吩,當然也可以自己new
一個LayoutParams
設置給contentView
。
底部對話框效果
如果是要實現(xiàn)底部圓角對話框妒蔚,原理也相似穿挨,只需要給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();
}
底部圓角對話框效果
源碼:https://github.com/xiaoyanger0825/BottomDialog