AlertDialog styling - как изменить стиль (цвет) названия, сообщения и т.д.
Я немного поразмыслил над этим. Мне нужно сделать, изменить стиль всех AlertDialog
в моем приложении Android. Диалоговый фон должен быть белым, а текст должен быть черным. Я пробовал создавать множество стилей, тем и применять код, манифест и т.д., Но не добился успеха в отношении цветов текста внутри AlertDialog
. Прямо сейчас у меня самый простой из кодов:
манифеста:
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
styles.xml:
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:alertDialogStyle">@style/DialogStyle</item>
</style>
<style name="DialogStyle" parent="@android:style/Theme.Dialog">
<!-- changing these background stuff works fine -->
<item name="android:bottomBright">@android:color/white</item>
<item name="android:bottomDark">@android:color/white</item>
<item name="android:bottomMedium">@drawable/dialog_footer_bg</item>
<item name="android:centerBright">@android:color/white</item>
<item name="android:centerDark">@drawable/dialog_body_bg</item>
<item name="android:centerMedium">@android:color/white</item>
<item name="android:fullBright">@color/orange</item>
<item name="android:fullDark">@color/orange</item>
<item name="android:topBright">@color/green</item>
<item name="android:topDark">@drawable/dialog_header_bg</item>
Элементы, перечисленные ниже, не работают (прочитайте комментарии, которые я поставил над каждым элементом):
<!-- panelBackground is not getting set to null, there is something squarish around it -->
<item name="android:panelBackground">@null</item>
<!-- Setting this textColor doesn't seem to have any effect at all. Messages, title, button text color, whatever; nothing changes. -->
<item name="android:textColor">#000000</item>
<!-- Also tried with textAppearance, as follows. Didn't work -->
<item name="android:textAppearance">?android:attr/textColorPrimaryInverse</item>
<!-- Also tried changing textAppearancePrimary, to no avail -->
<item name="android:textColorPrimary">#000000</item>
<!-- Also need to change the dialog title text, tried it as follows, dint work: -->
<item name="android:windowTitleStyle">@style/DialogWindowTitle</item>
</style>
Диалоговое окно DialogWindowTitle определяется следующим образом:
<style name="DialogWindowTitle">
<item name="android:textAppearance">?android:attr/textAppearanceMediumInverse</item>
</style>
Поэтому никто из них не работает. Может ли кто-нибудь сказать мне, что я могу делать неправильно, и как я могу:
- Изменить цвет текста для сообщений (текст контента)
- Изменить цвет текста заголовка
- Удалите
панель фона
Примечание. Мне нужно поддерживать API 8 (2.2) вверх. Кроме того, я рассмотрел большую часть связанного с этим вопроса и группы google, но не могу понять, хотя у меня есть чувство, что оно прямо под моим носом!
Изменить: добавление снимка экрана:
![AlertDialog not themed as expected]()
Ответы
Ответ 1
Вам нужно определить тему для вашего AlertDialog и указать ее в теме своей деятельности. Атрибут alertDialogTheme
, а не alertDialogStyle
. Вот так:
<style name="Theme.YourTheme" parent="@android:style/Theme.Holo">
...
<item name="android:alertDialogTheme">@style/YourAlertDialogTheme</item>
</style>
<style name="YourAlertDialogTheme">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:windowMinWidthMajor">@android:dimen/dialog_min_width_major</item>
<item name="android:windowMinWidthMinor">@android:dimen/dialog_min_width_minor</item>
<item name="android:windowTitleStyle">...</item>
<item name="android:textAppearanceMedium">...</item>
<item name="android:borderlessButtonStyle">...</item>
<item name="android:buttonBarStyle">...</item>
</style>
Вы сможете изменить цвет и текст для заголовка, сообщения, и у вас будет некоторый контроль на фоне каждой области. Я написал сообщение в блоге, в котором подробно описаны шаги по созданию AlertDialog.
Ответ 2
Удалите фоновый рисунок панели
<item name="android:windowBackground">@color/transparent_color</item>
<color name="transparent_color">#00000000</color>
Это Мистил:
<style name="ThemeDialogCustom">
<item name="android:windowFrame">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:windowBackground">@color/transparent_color</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
<item name="android:colorBackgroundCacheHint">@null</item>
</style>
Что я добавил в конструктор.
Добавить textColor:
<item name="android:textColor">#ff0000</item>
Ответ 3
Вы должны добавить стиль к конструктору диалогового окна
builder = new AlertDialog.Builder(this, R.style.DialogStyle);
Ответ 4
Я изменил цвет программно таким образом:
var builder = new AlertDialog.Builder (this);
...
...
...
var dialog = builder.Show ();
int textColorId = Resources.GetIdentifier ("alertTitle", "id", "android");
TextView textColor = dialog.FindViewById<TextView> (textColorId);
textColor?.SetTextColor (Color.DarkRed);
как alertTitle, вы можете изменить другие данные таким образом (следующий пример для titleDivider):
int titleDividerId = Resources.GetIdentifier ("titleDivider", "id", "android");
View titleDivider = dialog.FindViewById (titleDividerId);
titleDivider?.SetBackgroundColor (Color.Red);
это в С#, но в java это одно и то же.
Ответ 5
На основе ответа @general03 вы можете использовать встроенный стиль Android, чтобы быстро настроить диалог. Темы диалогов можно найти в разделе android.R.style.Theme_DeviceDefault_Dialogxxx
.
Например:
builder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Dialog_MinWidth);
builder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Dialog_NoActionBar);
builder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_DialogWhenLarge);
Ответ 6
Это зависит от того, сколько вы хотите настроить диалог оповещения. У меня есть разные шаги для настройки диалогового окна предупреждения. Пожалуйста, посетите: fooobar.com/questions/165099/...
![введите описание изображения здесь]()
Ответ 7
Используйте это в своем стиле в значениях-v21/style.xml
<style name="AlertDialogCustom" parent="@android:style/Theme.Material.Dialog.NoActionBar">
<item name="android:windowBackground">@android:color/white</item>
<item name="android:windowActionBar">false</item>
<item name="android:colorAccent">@color/cbt_ui_primary_dark</item>
<item name="android:windowTitleStyle">@style/DialogWindowTitle.Sphinx</item>
<item name="android:textColorPrimary">@color/cbt_hints_color</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="android:windowMinWidthMajor">@android:dimen/dialog_min_width_major</item>
<item name="android:windowMinWidthMinor">@android:dimen/dialog_min_width_minor</item>
</style>
Ответ 8
Здесь мой код для темы диалогового окна предупреждения:
<style name="alertDialog" parent="Theme.AppCompat.Dialog.Alert">
<item name="android:background">@color/light_button_text_color</item>
<item name="android:textColor">@android:color/black</item>
<item name="android:textColorPrimary">@android:color/black</item>
<item name="android:textColorSecondary">@android:color/black</item>
<item name="android:titleTextColor" tools:targetApi="m">@android:color/black</item>
</style>
Поместите этот код в styles.xml.
В вашем java примените эту тему как:
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.alertDialog);
Вывод кода