DialogFragment 占用整个屏幕宽度

DialogFragment takes whole screen width

在我的 android 应用程序中,我使用扩展 class 的 DialogFragment 来显示自定义对话框,但我有一个问题,所有创建的对话框都占用整个屏幕宽度(照片中的示例),我更喜欢有保证金,怎么办?

my dialog

一种方法是为其使用样式。您可以创建自定义样式,例如

<style name="AlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    <!-- Used for the buttons -->
    <item name="colorAccent">@color/black</item>
    <item name="android:textColorPrimary">@color/black</item>
    <item name="android:windowMinWidthMajor">80%</item>
    <item name="android:windowMinWidthMinor">80%</item>
    <!-- Used for the background -->
    <item name="android:windowBackground">@color/white</item>
</style> 
您的 DialogFragment 子类的

onCreate 您可以将其作为参数提供

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setStyle(STYLE_NORMAL, R.style.AlertDialogStyle)

您可以在样式中找到关键项目的描述here