更改警告对话框的文本颜色

54

我在我的应用程序中有一个弹出窗口,用于下载音频说明。我正在尝试更改“确定”默认文本颜色为蓝色。我尝试过一些方法,但它们都不起作用。这是我的代码:

 private void showDownloadPgmPopup() {

    android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getActivity());
    builder.setTitle("Download instructional audio?");
    builder.setMessage(ParamConstants.AUDIODOWNLOADPERMISSION);
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            WwDatabaseHelper.storeSelectedWeekAndDay(getActivity(), mSelectedWeekDataModel);
            goToMoveScreen();
        }
    });
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            AndroidDownloadFileByProgressBarActivity.StartAudioAssetDownload(getActivity());

        }

    }).create();
    // change the text color of download instruction ok button


    final android.app.AlertDialog dialog = builder.show();
    dialog.setOnShowListener( new DialogInterface.OnShowListener() {
                                  @Override
                                  public void onShow(DialogInterface arg0) {
                                      dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.parseColor("#ff5722"));
                                  }
                              });
    dialog.setCanceledOnTouchOutside(false);
    dialog.show();
}

但是更改没有生效,有人能告诉我我做错了什么吗?


可能是重复的问题:如何在Android中创建自定义对话框? - SaravInfern
10个回答

44

在AlertDialog构造函数中,您必须提供自定义样式ID:

AlertDialog.Builder(Context context, int themeResId)

而样式文件应该是类似于:

<style name="AlertDialogCustom" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:colorAccent">#0000FF</item>
</style>

另一个建议是使用具有 <item name="alertDialogTheme">@style/MyStyle</item> 的主题,其中 MyStyle 应该类似于 **<style name="MyStyle" parent="ThemeOverlay.AppCompat.Dialog.Alert"> </style>**(警告:android:alertDialogTheme 会自动完成但不起作用!) - Top-Master

33
改变你的方法为:
private void showDownloadPgmPopup() {

    android.app.AlertDialog.Builder builder = new android.app
               .AlertDialog.Builder(getActivity(),R.style.AlertDialog);
...
..
.   
}

在res/values/styles.xml下添加一个新的AlertDialog样式

<style name="AlertDialog" parent="Base.Theme.AppCompat.Light.Dialog">
        <item name="android:textColor">#000000</item>
        <item name="android:textColorPrimary">#595959</item>
        <item name="android:colorAccent">#1b5e20</item>
    </style>

以下是这些更改的屏幕截图

查看对话框颜色更改


15

尝试在show后调用setTextColor。请参考下面的示例:

show()
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.YELLOW)

2
太好了!!! 谢谢。对我有用。因为我正在使用材料设计主题,其他答案都不起作用。 - sibin

7

你有两种方法来做到这一点

  1. 覆盖默认对话框。
//1. create a dialog object 'dialog'
MyCustomDialog builder = new MyCustomDialog(getActivity(), "Exit", 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.parseColor("#f34235"));
    }
}

dialog.show()

创建自己的“自定义”对话框。
// create instance of dialog
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

// get inflater and inflate layour for dialogue 
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);

// now set layout to dialog
dialogBuilder.setView(dialogView);

// create instance like this OR directly mentioned in layout
Button button= (Button) dialogView.findViewById(R.id.label_field);
button.setText("test label");
AlertDialog alertDialog = dialogBuilder.create();

// show dialog
alertDialog.show();

4

我可以通过使用SpannableString替换普通字符串来将文本颜色更改为红色。

示例 -

var okString = new SpannableString("OK");
okString.SetSpan(new ForegroundColorSpan(Color.Red), 0, Strings.Report.Length, 0);

然后我将变量okString传递给了setItems()。

尝试将spannableString传递给setPositiveButton()。


2

简单来说,您只需使用以下代码更改“OK”文本:

Html.fromHtml("<font color='#0000FF'>OK</font>")

该代码将根据您添加的颜色值完全更改文本颜色,而#0000FF表示蓝色。


在我的情况下,颜色被忽略了。不确定为什么。 - Brian Reinhold
我曾经遇到过同样的问题,所以我不得不使用SpannableString中的setSpan方法。 - Fred

1
这里是如何使用 MaterialAlertDialogBuilder 来显示和自定义您的 AlertDialog。
如果您想了解更多细节,一定要在此处查看。 https://www.journaldev.com/309/android-alert-dialog-using-kotlin
val builder = MaterialAlertDialogBuilder(requireContext())
with(builder) {
    setTitle(R.string.log_out)
    setMessage(R.string.dialog_msg_logout)
    setPositiveButton(R.string.confirm) { _, _ ->
        logoutUser()
    }
    setNegativeButton(R.string.cancel, null)
}

val dialog = builder.create()
dialog.show()

val button = dialog.getButton(DialogInterface.BUTTON_POSITIVE)
with(button) {
    setTextColor(ContextCompat.getColor(requireContext(), R.color.colorAccent))
}

enter image description here


1
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.YELLOW)

上面的代码对我来说不起作用,但下面的代码确实有效:
dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.Yellow));

1
使用Material Components库,只需使用buttonBarPositiveButtonStyle属性定义自定义样式即可:
  <!-- Alert Dialog -->
  <style name="MaterialAlertDialog_OK_color" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
    <!-- Style for positive button -->
    <item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle.textColor</item>
  </style>

  <style name="PositiveButtonStyle.textColor" parent="@style/Widget.MaterialComponents.Button.TextButton.Dialog">
    <item name="android:textColor">@color/......</item>
  </style>

然后:

 new MaterialAlertDialogBuilder(context,
        R.style.MaterialAlertDialog_OK_color)
        .setMessage("Message......")
        .setPositiveButton("ok", null)
        .setNegativeButton("Cancel", null)
        .show();

enter image description here


0

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