Изменение цвета кнопки AlertDialog.Builder

Я пытаюсь изменить цвет кнопки AlertDialog.Builder, но я не нашел способа сделать это.

Я хочу изменить цвет кнопок и заголовка на белый, как в теме HOLO.

см. эти 2 скриншота в качестве примеров:

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

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

Я смотрел сюда:

Как изменить тему для AlertDialog

Измените стиль AlertDialog

Как изменить фон диалогового окна настраиваемого предупреждения

Применение стилей Android

Все они у меня не работают.

Вот мой код:

public void logInDialog()
{
    ContextThemeWrapper ctw = new ContextThemeWrapper( this,  R.style.dialogStyle);
    AlertDialog.Builder builder = new AlertDialog.Builder(ctw);
    builder.setTitle("Log in");
    View prefView = View.inflate(this, R.layout.log_in, null);  
    //The rest of the code.........
}

Это мой код стиля:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="dialogStyle" parent="android:Theme.Dialog">
        <item name="android:background">@color/white</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:button">@color/white</item>
    </style>    
</resources>

person dasdasd    schedule 27.07.2013    source источник


Ответы (4)


Я знаю, что это очень старый вопрос, но я столкнулся с той же проблемой и нашел решение. Чтобы изменить цвет текста внутри кнопки диалогового окна Alert, вы должны сделать что-то вроде этого:

public void logInDialog()
{
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    LayoutInflater inflater = context.getLayoutInflater();

    //setting custom view for our dialog
    View myview = inflater.inflate(R.layout.YOUR_CUSTOM_LAYOUT, null);
    builder.setNeutralButton(android.R.string.cancel, null);
    builder.setView(myview);

    //creating an alert dialog from our builder.
    AlertDialog dialog = builder.create();
    dialog.show();

    //retrieving the button view in order to handle it.
    Button neutral_button = dialog.getButton(DialogInterface.BUTTON_NEUTRAL);

    Button positive_button = dialog.getButton(DialogInterface.BUTTON_POSITIVE);


    if (neutral_button != null) {
        neutral_button.setBackgroundDrawable(context.getResources()
                        .getDrawable(R.drawable.custom_background));

        neutral_button.setTextColor(context.getResources()
                        .getColor(android.R.color.white));
    }
    if (positive_button != null) {
        positive_button.setBackgroundDrawable(context.getResources()
                        .getDrawable(R.drawable.custom_background));

        positive_button.setTextColor(context.getResources()
                        .getColor(android.R.color.white));
    }

}

И xmls для вашей кнопки использовал:

custom_background.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:drawable="#000000"/>
    <item android:drawable="@drawable/selectable_item_background"/>

</layer-list>

И selectable_item_background.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/item_pressed" android:state_pressed="true"/>
    <item android:drawable="@drawable/item_focused" android:state_focused="true"/>
    <item android:drawable="@drawable/item_focused" android:state_selected="true"/>
    <item android:drawable="@android:color/transparent"/>

</selector>

Я лично использовал этот код внутри фрагмента, поэтому у меня есть LayoutInflater. В вашем случае вы можете пропустить этот шаг. Надеюсь, это поможет другим людям в будущем.

person loumaros    schedule 06.04.2014

Чтобы продолжить ответ @Ioumaros, setBackgroundDrawable теперь устарел. Вы можете добиться того же изменения цвета фона с помощью этого кода:

    Button negativeButton = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
    negativeButton.setBackgroundColor(getResources().getColor(R.color.colorBackground));

    Button positiveButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
    positiveButton.setBackgroundColor(getResources().getColor(R.color.colorBackground));

Но выполнение этого программным способом обычно не считается лучшим способом ...

person Lara Ruffle Coles    schedule 25.02.2016

Чтобы изменить цвет кнопок AlertDialog.

// Initialize AlertDialog & AlertDialog Builder
AlertDialog.Builder builder = new AlertDialog.Builder(YourActivity.this);
builder.setTitle(R.String.AlertDialogTitle);
...........
......... 
//Build your AlertDialog 
AlertDialog Demo_alertDialog= builder.create();
Demo_alertDialog.show();

//For Positive Button:
Button b_pos; 
b_pos=Demo_alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
if(b_pos!=null){
   b_pos.setTextColor(getResources().getColor(R.color.YourColor));
   }    


//For Neutral Button:
Button b_neu;
b_neu=Demo_alertDialog.getButton(DialogInterface.BUTTON_NEUTRAL);
if(b_neu!=null){
   b_neu.setTextColor(getResources().getColor(R.color.YourColor));
   }

//For Negative Button:
Button b_neg;
b_neg=Demo_alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
if(b_neg!=null){
   b_neg.setTextColor(getResources().getColor(R.color.YourColor));
   }

Удачного кодирования :)

person Venkatesh Selvam    schedule 03.11.2015

после alertDialog.show ();

Button buttonNegative= alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);  
buttonNegative.setBackgroundColor(Color.RED);

or

buttonNegative.setBackgroundColor(getResources().getColor(R.color.red));
person vitalinvent    schedule 01.10.2019