android之更改对话框按钮颜色

现男友 阅读:19 2024-02-27 23:08:18 评论:0

有什么方法可以更改默认对话框按钮的颜色,还是我需要为此进行自定义对话框?

这是我的对话框:

private void removeItem(final int position) { 
    /** Create dialog which ask if user is sure about delete name from list **/ 
    AlertDialog.Builder builder = new AlertDialog.Builder(this); 
    builder.setTitle("Delete player"); 
    builder.setIcon(R.mipmap.ic_launcher); 
    builder.setMessage("Do you want to delete player: \"" + mNameList.get(position).getText1() + "\"?") 
            .setCancelable(false) 
 
            /** If user click "ok" button, delete player from list and save changes **/ 
            .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
                @Override 
                public void onClick(DialogInterface dialogInterface, int i) { 
                    mNameList.remove(position); 
                    mAdapter.notifyItemRemoved(position); 
                    saveData(); 
                } 
            }) 
 
            /** If user click "cancel" button, name won't delete from list **/ 
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
                @Override 
                public void onClick(DialogInterface dialogInterface, int i) { 
                    dialogInterface.dismiss(); 
                } 
            }); 
 
    /** Create Dialog **/ 
    AlertDialog alert = builder.create(); 
    alert.show(); 
} 

请您参考如下方法:

您可以使用 MaterialAlertDialogBuilder Material Components library 提供允许创建 Material AlertDialog .

只需使用:

   new MaterialAlertDialogBuilder(MainActivity.this, 
       R.style.MyThemeOverlay_MaterialComponents_MaterialAlertDialog) 
              .setTitle("Dialog") 
              .setMessage("Lorem ipsum dolor ....") 
              .setPositiveButton("Ok", /* listener = */ null) 
              .setNegativeButton("Cancel", /* listener = */ null) 
              .show(); 

然后定义您的自定义样式,使用 buttonBarPositiveButtonStyle buttonBarNegativeButtonStyle 属性:
  <!-- Alert Dialog --> 
  <style name="MyThemeOverlay.MaterialComponents.MaterialAlertDialog" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog"> 
     <item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item> 
     <item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item> 
     <item name="buttonBarNeutralButtonStyle">....</item> 
  </style> 
 
 
  <style name="PositiveButtonStyle" parent="@style/Widget.MaterialComponents.Button.TextButton.Dialog"> 
    <item name="android:textColor">#FFFFFF</item> 
    <item name="backgroundTint">#00f</item> 
  </style> 
 
  <style name="NegativeButtonStyle" parent="@style/Widget.MaterialComponents.Button.TextButton.Dialog"> 
    <item name="android:textColor">@color/colorAccent</item> 
    <item name="backgroundTint">@color/secondaryColor</item> 
  </style> 


标签:Android
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号