更改AlertDialog中按钮的颜色

56

如何在 Android 的 AlertDialog 中更改按钮的颜色?


18个回答

77

这是我所做的方法。

AlertDialog.Builder customBuilder = new AlertDialog.Builder(new ContextThemeWrapper(this,android.R.style.Theme_Dialog));

customBuilder.setTitle(R.string.popup_error_title);
customBuilder.setNegativeButton("Exit application", new DialogInterface.OnClickListener() {  
    public void onClick(DialogInterface dialog, int which) {  
        MyActivity.this.finish();
    }  
});

AlertDialog dialog = customBuilder.create();
dialog.show();

Button b = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);

if(b != null) {
    b.setBackgroundDrawable(getResources().getDrawable(R.drawable.my_button));
}

我在这里找到了可绘制的Android标准按钮不同颜色的方法


2
嗨,我也是这样应用按钮的背景图像。但是如果我应用图像,按钮底部会出现一些不必要的边距。如果我使用背景颜色,它就可以正常工作。我检查了按钮图像,它没问题。所以你能建议任何解决方案吗? - Raj
@Raj,你有没有找到解决这个不必要的边距的方法? - Deepak
@Deepak:目前还没有找到任何解决方案。如果您找到了,请告诉我。 - Raj
1
setBackgroundDrawable(Drawable)在API 16级中已被弃用;如果您不针对API级别低于16,请使用setBackground(Drawable)。 - Engin Yapici
setOnShowListener比检查null更好。仍然是个好答案。 - Zar E Ahmer
@Deepak 对于顶部边距,请检查其是否为非空,并将可见性设置为GONE:alertDialog.findViewById(android.R.id.title); - Rafael Ruiz Muñoz

18

由于大多数人现在可能正在使用DialogFragment,我遇到了一些问题,并通过查阅几篇SO答案来解决这些问题。让我发布我的当前解决方案。

最终,我采用已经建议几次的自定义可绘制的按钮背景来设置按钮背景。然而,在DialogFragmentonCreateDialog方法中还不可能这样做。您可以在onStart()中或者(这是我更喜欢的方式)在对话框的onShow监听器中执行此操作!请注意,之后您需要使按钮失效。

至于边距:只需在按钮的Drawable-XML中删除填充即可。

#在DialogFragment中的onCreateDialog:

@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
  AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

  // setup your dialog here...

  builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
    @Override
    public void onClick(final DialogInterface dialog, final int which) {
      // do something
    }
  });

  builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
    @Override
    public void onClick(final DialogInterface dialog, final int which) {
      // do something
    }
  });

  final AlertDialog dialog = builder.create();

  dialog.setOnShowListener(new DialogInterface.OnShowListener() {
    @Override
    public void onShow(final DialogInterface dialog) {
      Button negativeButton = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_NEGATIVE);
      Button positiveButton = ((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE);

      // this not working because multiplying white background (e.g. Holo Light) has no effect
      //negativeButton.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);

      final Drawable negativeButtonDrawable = getResources().getDrawable(R.drawable.alert_dialog_button_light_red);
      final Drawable positiveButtonDrawable = getResources().getDrawable(R.drawable.alert_dialog_button_light_green);
      if (Build.VERSION.SDK_INT >= 16) {
        negativeButton.setBackground(negativeButtonDrawable);
        positiveButton.setBackground(positiveButtonDrawable);
      } else {
        negativeButton.setBackgroundDrawable(negativeButtonDrawable);
        positiveButton.setBackgroundDrawable(positiveButtonDrawable);
      }

      negativeButton.invalidate();
      positiveButton.invalidate();
    }
  });

  return dialog;
}

一个按钮的可绘制XML示例:

<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">

  <item android:state_pressed="true" >
    <shape>
      <gradient
        android:startColor="@color/alert_dialog_button_green_pressed1"
        android:endColor="@color/alert_dialog_button_green_pressed2"
        android:angle="270" />
    </shape>
  </item>

  <item android:state_focused="true" >
    <shape>
      <gradient
        android:endColor="@color/alert_dialog_button_green_focused1"
        android:startColor="@color/alert_dialog_button_green_focused2"
        android:angle="270" />
    </shape>
  </item>

  <item>
    <shape>
      <gradient
        android:endColor="@color/alert_dialog_button_green1"
        android:startColor="@color/alert_dialog_button_green2"
        android:angle="270" />
    </shape>
  </item>
</selector>

别忘了在res\values\colors.xml中定义你的颜色,例如像这样(我不想要渐变,因此颜色1和2是相同的):

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="alert_dialog_button_green1">#b4099930</color>
  <color name="alert_dialog_button_green2">#b4099930</color>
  <color name="alert_dialog_button_green_focused1">#96099930</color>
  <color name="alert_dialog_button_green_focused2">#96099930</color>
  <color name="alert_dialog_button_green_pressed1">#96099930</color>
  <color name="alert_dialog_button_green_pressed2">#96099930</color>
</resources>

17

我已经通过这段代码实现了它,希望能对你有所帮助:

AlertDialog.Builder builder1 = new AlertDialog.Builder(this); 
        builder1.setCancelable(true);
     builder1.setTitle("abc");
      builder1.setMessage("abcdefg");
      builder1.setInverseBackgroundForced(true);
     builder1.setPositiveButton("Yes",
             new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {
             dialog.cancel();
         }
     }); 

     builder1.setNegativeButton("No",
             new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {
             dialog.cancel();
         }
     });

     AlertDialog alert11 = builder1.create();
     alert11.show(); 

     Button buttonbackground = alert11.getButton(DialogInterface.BUTTON_NEGATIVE); 
     buttonbackground.setBackgroundColor(Color.BLUE); 

     Button buttonbackground1 = alert11.getButton(DialogInterface.BUTTON_POSITIVE); 
     buttonbackground1.setBackgroundColor(Color.BLUE);

对我很有用,而且这是最简单的方法!您还可以使用此方法在按钮上设置setTextColor()。 - Ziad H.

11

我希望通过主题解决这个问题,而不是使用额外的代码,因为我认为将所有与样式相关的内容放在styles.xml文件中更加清晰。我的做法基于Arade的答案和这个问题

<style name="AlertDialogDanger" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="colorAccent">@color/error</item>
</style>

这将更改使用样式AlertDialogDanger创建的任何警报对话框中按钮文本的颜色。要实现此操作:

    new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogDanger))
            .setMessage("Really delete?")
            .setPositiveButton("Delete", null)
            .setNegativeButton("Cancel", null)
            .create().show();

我们可以使用主题为正面、负面和中性按钮设置不同的颜色吗? - Hemant Kaushik

9

以下是一些示例:

AlertDialog.Builder b = new AlertDialog.Builder(all.this);

b.setMessage("r u wan't 2 exit");
b.setCancelable(false);

b.setNegativeButton("no", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();    
    }
});

b.setPositiveButton("yes", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        Intent i=new Intent(getBaseContext(), s.class);
        startActivity(i);
    }
});

AlertDialog a=b.create();

a.show();

Button bq = a.getButton(DialogInterface.BUTTON_NEGATIVE);  
bq.setBackgroundColor(Color.BLUE);

7
我们可以使用样式更改警告对话框按钮文本颜色。
 AlertDialog.Builder dialog = new AlertDialog.Builder(context, R.style.yourDialog);
    dialog.setTitle(R.string.title);
    dialog.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            //code here 
        }
    });
    dialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            //do here 
        }
    });

    dialog.show();

Style.xml

<style name="yourDialog" parent="Theme.AppCompat.Light.Dialog.Alert">

    <item name="android:colorAccent">@color/themeColor</item>
    <item name="android:colorPrimary">@color/themeColor</item>

</style>

这将适用于所有API:<style name="AppTheme.Dialog" parent="Theme.AppCompat.Light.Dialog.Alert"> <item name="colorAccent">@color/colorPrimary</item> <item name="colorPrimary">@color/colorPrimary</item> </style> - Waqar Khan
不支持 API 30 和 S9+。 - AtomicallyBeyond

4
有两种方法可以完成它:
  1. 通过代码:
        val builder = AlertDialog.Builder(activity!!)
        ...
        val dialog = builder.create()
                .apply {
                    setOnShowListener {
                        getButton(Dialog.BUTTON_NEGATIVE)?.setTextColor(...)
                    }
                }


通过XML:
    <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
        ...
        <item name="materialAlertDialogTheme">@style/ThemeOverlay.MyApp.MaterialAlertDialog</item>
    </style>

    <style name="ThemeOverlay.MyApp.MaterialAlertDialog" parent="ThemeOverlay.MaterialComponents.MaterialAlertDialog">
        <item name="dialogCornerRadius">6dp</item>
        <item name="buttonBarNegativeButtonStyle">@style/Widget.MyApp.NegativeButton</item>
        <item name="buttonBarPositiveButtonStyle">@style/Widget.MyApp.PositiveButton</item>
    </style>

    <style name="Widget.MyApp.NegativeButton" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
        <item name="materialThemeOverlay">@style/ThemeOverlay.MyApp.NegativeButton</item>
    </style>

    <style name="Widget.MyApp.PositiveButton" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
        <item name="materialThemeOverlay">@style/ThemeOverlay.MyApp.PositiveButton</item>
    </style>

    <style name="ThemeOverlay.MyApp.NegativeButton" parent="">
        <item name="colorPrimary">#f00</item>
    </style>

    <style name="ThemeOverlay.MyApp.PositiveButton" parent="">
        <item name="colorPrimary">#00f</item>
    </style>

使用方法:

AlertDialog.Builder(this).setTitle("title").setMessage("message").setPositiveButton("positive", null)
                .setNegativeButton("negative", null).show()

或者,如果您不想将样式作为默认样式:
AlertDialog.Builder(this, R.style.ThemeOverlay_MyApp_MaterialAlertDialog).setTitle("title")
            .setMessage("message").setPositiveButton("positive", null)
            .setNegativeButton("negative", null).show()

3

也许有人已经以这种方式回答了,但在我的眼中,我没有找到,所以我更喜欢这个答案,它非常有效。请记住,在dialog.show()之后应用setTextColor,否则会出现问题。

    dialog.show(); //Only after .show() was called

    dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(neededColor);
    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(neededColor);

2
    //el resto
    AlertDialog a=alertDialog.create();
    cambiar_color_texto_alertdialog(a);

}

public void cambiar_color_texto_alertdialog(AlertDialog a){
    a.show();
    Button BN = a.getButton(DialogInterface.BUTTON_NEGATIVE);
    BN.setTextColor(parseColor("#2E9AFE"));
    Button BA = a.getButton(DialogInterface.BUTTON_POSITIVE);
    BA.setTextColor(parseColor("#2E9AFE"));
}

2

使用AppCompat,还可以更改按钮和其他文本的颜色:

<style name="AlertDialogCustom" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:colorPrimary">@color/flexdrive_blue_1</item>
    <item name="android:textColorPrimary">@color/flexdrive_blue_6</item>
    <item name="android:colorAccent">@color/flexdrive_blue_1</item>
    <item name="colorPrimaryDark">@color/flexdrive_blue_4</item>
</style>

我们可以使用主题为正面、负面和中性按钮设置不同的颜色吗? - Hemant Kaushik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接