Как изменить цвет текста кнопки диалога по умолчанию в android 5
У меня есть много предупреждений в моем приложении. Это макет по умолчанию, но я добавляю в диалог положительные и отрицательные кнопки. Таким образом, кнопки получают цвет текста по умолчанию для Android 5 (зеленый). Я попытался изменить его без успеха. Любая идея, как изменить цвет текста?
Мое пользовательское диалоговое окно:
public class MyCustomDialog extends AlertDialog.Builder {
public MyCustomDialog(Context context,String title,String message) {
super(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View viewDialog = inflater.inflate(R.layout.dialog_simple, null, false);
TextView titleTextView = (TextView)viewDialog.findViewById(R.id.title);
titleTextView.setText(title);
TextView messageTextView = (TextView)viewDialog.findViewById(R.id.message);
messageTextView.setText(message);
this.setCancelable(false);
this.setView(viewDialog);
} }
Создание диалога:
MyCustomDialog builder = new MyCustomDialog(getActivity(), "Try Again", errorMessage);
builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
...
}
}).show();
Этот negativeButton является диалоговой кнопкой по умолчанию и принимает зеленый цвет по умолчанию с Android 5 Lollipop.
Большое спасибо
![Custom dialog with green button]()
Ответы
Ответ 1
Вы можете сначала попытаться создать объект AlertDialog
, а затем использовать его, чтобы настроить изменение цвета кнопки, а затем показать его. (Обратите внимание, что на объекте builder
вместо вызова show()
мы вызываем create()
чтобы получить объект AlertDialog
:
//1. create a dialog object 'dialog'
MyCustomDialog builder = new MyCustomDialog(getActivity(), "Try Again", errorMessage);
AlertDialog dialog = builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
...
}
}).create();
//2. now setup to change color of the button
dialog.setOnShowListener( new OnShowListener() {
@Override
public void onShow(DialogInterface arg0) {
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(COLOR_I_WANT);
}
});
dialog.show()
Причина, по которой вы должны сделать это в onShow()
и не можете просто получить эту кнопку после создания диалогового окна, заключается в том, что кнопка еще не была создана.
Я изменил AlertDialog.BUTTON_POSITIVE
на AlertDialog.BUTTON_NEGATIVE
чтобы отразить изменение в вашем вопросе. Хотя странно, что кнопка "ОК" будет отрицательной кнопкой. Обычно это положительная кнопка.
Ответ 2
Вот естественный способ сделать это со стилями:
Если ваша AppTheme
унаследована от Theme.MaterialComponents
, то:
<style name="AlertDialogTheme" parent="ThemeOverlay.MaterialComponents.Dialog.Alert">
<item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
<item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
</style>
<style name="NegativeButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
<item name="android:textColor">#f00</item>
</style>
<style name="PositiveButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
<item name="android:textColor">#00f</item>
</style>
Если ваш AppTheme
унаследован от Theme.AppCompat
:
<style name="AlertDialogTheme" parent="ThemeOverlay.AppCompat.Dialog.Alert">
<item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
<item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
</style>
<style name="NegativeButtonStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
<item name="android:textColor">#f00</item>
</style>
<style name="PositiveButtonStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
<item name="android:textColor">#00f</item>
</style>
Используйте AlertDialogTheme
в своем AppTheme
<item name="alertDialogTheme">@style/AlertDialogTheme</item>
или в конструкторе
androidx.appcompat.app.AlertDialog.Builder(context, R.style.AlertDialogTheme)
Ответ 3
Цвет кнопок и другого текста также можно изменить с помощью темы:
значения-21/styles.xml
<style name="AppTheme" parent="...">
...
<item name="android:timePickerDialogTheme">@style/AlertDialogCustom</item>
<item name="android:datePickerDialogTheme">@style/AlertDialogCustom</item>
<item name="android:alertDialogTheme">@style/AlertDialogCustom</item>
</style>
<style name="AlertDialogCustom" parent="android:Theme.Material.Light.Dialog.Alert">
<item name="android:colorPrimary">#00397F</item>
<item name="android:colorAccent">#0AAEEF</item>
</style>
Результат:
![Dialog]()
![Date picker]()
Ответ 4
Самое простое решение:
dialog.show(); //Only after .show() was called
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(neededColor);
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(neededColor);
Ответ 5
Есть два способа изменить цвет кнопки диалога.
Основной путь
Если вы просто хотите изменить действие, напишите две следующие строки после alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.colorPrimary));
alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.colorPrimaryDark));
рекомендуемые
Я рекомендую добавить тему для AlertDialog
в styles.xml
чтобы вам не приходилось писать один и тот же код снова и снова при каждом вызове действия/диалога. Вы можете просто создать стиль и применить эту тему в диалоговом окне. Поэтому, когда вы захотите изменить цвет окна AlertDialog, просто измените цвет в styles.xml, и все диалоговые окна будут обновлены во всем приложении.
<style name="AlertDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="colorAccent">@color/colorPrimary</item>
</style>
И применить тему в AlertDialog.Builder
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogTheme);
Ответ 6
Если вы хотите изменить цвет текста кнопок (положительный, отрицательный, нейтральный), просто добавьте в свой стиль диалогового окна:
<item name="colorAccent">@color/accent_color</item>
Итак, ваш стиль диалога должен выглядеть так:
<style name="AlertDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:textColor">@android:color/black</item>
<item name="colorAccent">@color/topeka_accent</item>
</style>
Ответ 7
<style name="AlertDialogCustom" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:colorPrimary">#00397F</item>
<item name="android:textColorPrimary">#22397F</item>
<item name="android:colorAccent">#00397F</item>
<item name="colorPrimaryDark">#22397F</item>
</style>
Цвет кнопок и другого текста также можно изменить с помощью appcompat:
Ответ 8
Как примечание:
Цвета кнопок (и всего стиля) также зависят от текущей темы, которая может отличаться при использовании
android.app.AlertDialog.Builder builder = new AlertDialog.Builder()
или
android.support.v7.app.AlertDialog.Builder builder = new AlertDialog.Builder()
(лучше использовать второй)
Ответ 9
для меня это было другое, я использовал тему кнопки
<style name="ButtonLight_pink" parent="android:Widget.Button">
<item name="android:background">@drawable/light_pink_btn_default_holo_light</item>
<item name="android:minHeight">48dip</item>
<item name="android:minWidth">64dip</item>
<item name="android:textColor">@color/tab_background_light_pink</item>
</style>
и потому что
андроида: TextColor
был белый там... я не видел ни одного текста кнопки (кнопки диалога тоже в основном кнопки).
там мы идем, меняем его, исправляем.