首先在style.xml中定义一个对话框样式,这里可以修改颜色:
//对话框沾满整个屏幕的宽度 <style name="DialogShareTheme" parent="Theme.AppCompat.Dialog"> <item name="android:background">@color/white</item> <item name="android:windowBackground">@color/transparent</item> </style>
接着编写对话框的布局文件,这里就只写了一个按钮:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Test" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>
java代码中:
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(ProductionInformationActivity.this, R.style.DialogShareTheme); //加入样式 final View dialogView = LayoutInflater.from(ProductionInformationActivity.this).inflate(R.layout.dialog_share,null); //加入布局 dialogBuilder.setView(dialogView); Dialog dialog = dialogBuilder.create(); dialog.getWindow().setGravity(Gravity.BOTTOM); dialog.show(); WindowManager.LayoutParams p = dialog.getWindow().getAttributes(); p.width = MyApp.getScreenWidth(this); //设置dialog的宽度为当前手机屏幕的宽度 dialog.getWindow().setAttributes(p);
效果: