android - 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"
,似乎工作正常
解决方案
您可以尝试通过样式属性设置对话框的背景并使用MaterialAlertDialogBuilder
.
从内部删除android:background="@drawable/background_note"
属性ConstraintLayout
layout_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()
}
推荐阅读
- node.js - 使用 nodejs/react/socket 实现一个协作文本编辑器,但由于 heroku 服务器速度慢而遇到问题
- firebase - 解决方案应用程序不崩溃
- powerbi - 按关系和切片器过滤的度量或列
- apache-spark - 为什么 Spark 阶段只有一个功能。而不是在地图阶段进行如此多的转换
- key - 我无法通过 ssh 连接到 terraform 中新创建的 ec2 实例
- python - 检查数据集中的 NaN 输入时,输入类型不支持 ufunc 'isnan'
- python - 获取错误:由 NewConnectionError 引起(':无法建立新连接:[Errno 5] I/O 错误')当 requests.post 到 API
- java - 为什么制作 shell 脚本背景不能按预期工作
- python - Selenium 中的 get_elements_by_tag_name() 返回什么?
- html - 由于DIV框的空白,识别问题但无法解决