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

Учитывая функцию как

private void showInputDialog() {
    final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
    final EditText input = new EditText(getActivity());
    input.setSingleLine();
    FrameLayout container = new FrameLayout(getActivity());
    FrameLayout.LayoutParams params = new  FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    params.leftMargin= convertDpToPx(25);                                       //remember to scale correctly
    params.rightMargin= convertDpToPx(30);
    input.setLayoutParams(params);
    container.addView(input);
    alert.setTitle("Change City");
    alert.setMessage("Hey there, could not find the city you wanted. Please enter a new one:\n");
    alert.setView(container);
    alert.setPositiveButton("Go", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            changeCity(input.getText().toString());
        }
    });
    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });
    alert.show();
}

Теперь, когда я получаю этот AlertDialog.Builder в своем приложении, цвета кнопок зеленые (по умолчанию для Android 5), но цвет EditText розовый (R.color.coloraccent). Как изменить цвет кнопок на розовый?

Любая помощь будет оценена


person Sparker0i    schedule 08.10.2016    source источник
comment
установите стиль в alerdialog.   -  person sneha desai    schedule 08.10.2016


Ответы (3)


попробуй так

alertDialog.show(); 

Только после вызова .show(). попробуйте этот фрагмент

//for negative side button
    alertDialog.getButton(dialog.BUTTON_NEGATIVE).setTextColor(neededColor); 
//for positive side button
    alertDialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(neededColor);
person brahmy adigopula    schedule 08.10.2016

Вы можете тему это. Как вы заметили, кнопки по умолчанию используют акцентный цвет в вашей теме для textColor, чтобы изменить это, вы должны:

Измените тему вашего приложения в файле res/values/styles.xml.

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    ...
    <item name="buttonBarPositiveButtonStyle">@style/Base.Widget.AppCompat.Button.Borderless.MyStyle</item>
</style>

И добавьте свой стиль кнопки в тему кнопки AlertDialog.

<style name="Base.Widget.AppCompat.Button.Borderless.MyStyle">
    <item name="android:textColor">@color/colorAccent</item>
</style>

Примечание

Это повлияет на все AlertDialogs, а не только на один. Вы также можете создать новую отдельную тему и добавить в AlertDialog.Builder, например new AlertDialog.Builder(getActivity(), R.style.MyAlertDialogTheme)

person Pär Nils Amsen    schedule 08.10.2016
comment
Это не сработает, так как AlertDialog использует ?alertDialogTheme из AppTheme. Вам придется переопределить тему диалогового окна предупреждения и стиль кнопки внутри него. - person Eugen Pechanec; 08.10.2016

вам нужно добавить настраиваемый вид в окно предупреждения. создает файл макета с именем «my_custom_alert_window», затем выполните следующие действия:

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.my_custom_alert_window, null);
dialogBuilder.setView(dialogView);

Button btn = (Button) dialogView.findViewById(R.id.label_field);
btn.setBackgroundColor(....);
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();

затем вы можете изменить цвет фона кнопки, как показано выше.

person Amir Ziarati    schedule 08.10.2016