如何使用 appCompat 22.1 及更高版本中的新 AlertDialog 并为其设置样式 [英] How to use and style new AlertDialog from appCompat 22.1 and above
问题描述
我正在尝试从默认的 android AlertDialog
迁移到 appCompat-22.1 中包含的新版本到目前为止,我了解到您只需导入 android.support.v7.app.AlertDialog
包即可使用它.
I am trying to migrate from default android AlertDialog
to the new one included in appCompat-22.1
So far I understand you only have to import android.support.v7.app.AlertDialog
package in order to use it.
但是我该如何设计呢?例如更改正负按钮颜色、标题颜色、消息颜色和背景颜色?
But how can I style it? For example change the positive/negative button colors, title color, message color and background color?
推荐答案
在创建 AlertDialog
时,您可以设置要使用的主题.
When creating the AlertDialog
you can set a theme to use.
示例 - 创建对话框
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyAlertDialogStyle);
builder.setTitle("AppCompatDialog");
builder.setMessage("Lorem ipsum dolor...");
builder.setPositiveButton("OK", null);
builder.setNegativeButton("Cancel", null);
builder.show();
styles.xml - 自定义样式
<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
<!-- Used for the buttons -->
<item name="colorAccent">#FFC107</item>
<!-- Used for the title and text -->
<item name="android:textColorPrimary">#FFFFFF</item>
<!-- Used for the background -->
<item name="android:background">#4CAF50</item>
</style>
结果
编辑
为了更改标题的外观,您可以执行以下操作.首先添加一个新样式:
In order to change the Appearance of the Title, you can do the following. First add a new style:
<style name="MyTitleTextStyle">
<item name="android:textColor">#FFEB3B</item>
<item name="android:textAppearance">@style/TextAppearance.AppCompat.Title</item>
</style>
之后只需在您的 MyAlertDialogStyle
中引用此样式:
afterwards simply reference this style in your MyAlertDialogStyle
:
<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
...
<item name="android:windowTitleStyle">@style/MyTitleTextStyle</item>
</style>
通过这种方式,您可以通过 android:textColorPrimary
为消息定义不同的 textColor
,并通过样式为标题定义不同的 textColor
.
This way you can define a different textColor
for the message via android:textColorPrimary
and a different for the title via the style.
这篇关于如何使用 appCompat 22.1 及更高版本中的新 AlertDialog 并为其设置样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!