首页 > 解决方案 > Kotlin 的 AlertDialog 中的不同颜色背景

问题描述

我的自定义警报对话框发生了一件非常奇怪的事情。相同的代码在不同的时间运行时,会产生不同的警报对话框布局的背景颜色,其中大多数时候颜色是红色(无处不在!),即使我对布局使用了不同的背景。先看看我的代码。

这是 AlertDialog 的布局(layout_add_url.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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_margin="@dimen/_10sdp"
    android:id="@+id/url_layout_constraint"
    android:background="@drawable/background_note"
    android:layout_height="wrap_content">

//Some  ImageViews and TextViews here

这就是layout_add_url.xml最终

在此处输入图像描述

现在,

这是 background_note.xml

<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#333333"/>             //Note that the color here is black
    <corners android:radius="@dimen/_10sdp"/>
</shape>

这是我最终在 Kotlin Activity 中创建AlertDialog的地方

 val inflater = layoutInflater
            val view = inflater.inflate(R.layout.layout_add_url, null)
            val infoDialogBuilder = AlertDialog.Builder(this@CreateNotesActivity)
            infoDialogBuilder.setView(view)
            val infoDialog = infoDialogBuilder.create()
            infoDialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            infoDialog.setContentView(view)
            infoDialog.show()

但是在真实设备上运行项目之后。看起来像这样

在此处输入图像描述

注意 我注意到,当我更改android:background="@drawable/background_note"代码时android:background="#333333",似乎工作正常

标签: androidkotlinpopupwindow

解决方案


您可以尝试通过样式属性设置对话框的背景并使用MaterialAlertDialogBuilder.

从内部删除android:background="@drawable/background_note"属性ConstraintLayoutlayout_add_url

在以下位置定义您的对话框样式style.xml

<style name="style_dialog" parent="ThemeOverlay.MaterialComponents.Dialog.Alert">
    <item name="shapeAppearanceMediumComponent">@style/style_dialog_background</item>
    <item name="colorSurface">#333333</item>
</style>

<style name="style_dialog_background" parent="ShapeAppearance.MaterialComponents.MediumComponent">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">@dimen/_10sdp</item>
</style>

然后通过调用创建您的对话框:

val dialogView = layoutInflater.inflate(R.layout.layout_add_url, null)
MaterialAlertDialogBuilder(this@CreateNotesActivity, R.style.style_dialog)
        .setView(dialogView)
        .create().apply {
            show()
        }

推荐阅读