【问题标题】:Changing color of OK button in AlertDialog在 AlertDialog 中更改 OK 按钮的颜色
【发布时间】:2018-04-03 20:00:38
【问题描述】:

我正在尝试在 Android 中更改 AlertDialog 中正面 button 的颜色。在我的 S8 上,按钮本身是绿色的,但是当我尝试更改它时,无论我选择什么颜色,它都会变成亮紫色。(我尝试了许多不同深浅的蓝色甚至粉红色来测试)

我正在改变颜色:

dialog.getButton(DialogInterface.BUTTON_POSITIVE).textColor = R.color.color_blue

我在dialog.show()之后调用它。

【问题讨论】:

  • 我认为对话框文本颜色设置为由于应用程序主题,如果不更改colors.xml中的主题强调色,您将无法更改它

标签: android kotlin android-alertdialog android-textinputlayout


【解决方案1】:

我宁愿使用theme 来控制对话框的外观。你的情况

R.color.color_blue 是一个资源 ID。您必须将其转换为 color。例如

 dialog.getButton(DialogInterface.BUTTON_POSITIVE).textColor = ContextCompat.getColor(this, R.color.color_blue)

【讨论】:

    【解决方案2】:

    尝试以下方法,您可能会得到解决方案

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

    【讨论】:

      【解决方案3】:

      你可以尝试先创建AlertDialog对象,然后用它来设置改变按钮的颜色,然后显示出来。 (请注意,在 builder 对象上而不是调用 show() 我们调用 create() 来获取 AlertDialog 对象:

      //1. create a dialog object 'dialog'
      MyCustomDialog builder = new MyCustomDialog(getActivity(), "Try Again", 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_I_WANT);
          }
      });
      
      dialog.show()
      

      您必须在onShow() 上执行此操作并且在创建对话框后不能只获取该按钮的原因是该按钮尚未创建。

      我将AlertDialog.BUTTON_POSITIVE 更改为AlertDialog.BUTTON_NEGATIVE 以反映您问题的变化。虽然奇怪的是“确定”按钮会是一个否定按钮。通常是正面按钮。

      【讨论】:

        【解决方案4】:

        您可以为警报对话框设置自定义主题

        <style name="AlertDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
            <item name="android:colorPrimary">#FFFFFF</item>
            <item name="android:textColorPrimary">#FFFFFF</item>
            <item name="android:colorAccent">#FFFFFF</item>
            <item name="colorPrimaryDark">#FFFFFF</item>
        </style>
        

        根据您的选择设置颜色

        【讨论】:

          猜你喜欢
          • 2011-05-04
          • 2020-01-01
          • 2018-07-08
          • 2023-03-05
          • 2020-08-03
          • 2014-07-11
          相关资源
          最近更新 更多