3

Как изменить цвет кнопок в АлертДиалоге?

На данный момент диалог выглядит вот так

В разметке диалога задаю

android:background="@color/background_window"

все, кроме кнопок подсвечивается серым цветом

пробую вот так:

dialog.getButton(DialogInterface.BUTTON_POSITIVE).setBackgroundColor(ContextCompat.getColor(MyApplication.getAppContext(), R.color.background_window));

приложение падает при открытии диалога

Заранее спасибо

2 ответа 2

3

Решение выше перекрашивает только бакграунд у кнопок

введите сюда описание изображения

По сути ответ на вопрос был закоментирован в ответе выше

Перед открытием диалога вставил строчку:

dialog.getWindow().setBackgroundDrawableResource(R.color.background_window);

и все заработало:

введите сюда описание изображения

Странно, что строка в разметке не устанавливает бэкграунд для панели кнопок

1

На en-SO пишут, что можно повесить слушатель показа диалога и уже в нём менять фон кнопкам, т.к. в этот момент диалог уже создан.

AlertDialog.Builder adb = new AlertDialog.Builder(context1);
    adb.setTitle(context1.getString(R.string.app_name))
    .setMessage(message)
    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
});
AlertDialog dialog = adb.create();

// Make some UI changes for AlertDialog
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
    @Override
    public void onShow(final DialogInterface dialog) {

        // Add or create your own background drawable for AlertDialog window
        //Window view = ((AlertDialog)dialog).getWindow();
        //view.setBackgroundDrawableResource(R.drawable.your_drawable);

        // Customize POSITIVE, NEGATIVE and NEUTRAL buttons.
        Button positiveButton = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE);
        positiveButton.setTextColor(context1.getResources().getColor(R.color.primaryColor));
        positiveButton.setTypeface(Typeface.DEFAULT_BOLD);
        positiveButton.invalidate();

        Button negativeButton = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE);
        negativeButton.setTextColor(context1.getResources().getColor(R.color.primaryColor));
        negativeButton.setTypeface(Typeface.DEFAULT_BOLD);
        negativeButton.invalidate();

        Button neutralButton = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEUTRAL);
        neutralButton.setTextColor(context1.getResources().getColor(R.color.primaryColor));
        neutralButton.setTypeface(Typeface.DEFAULT_BOLD);
        neutralButton.invalidate();
    }
});

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.