【发布时间】:2011-05-04 23:46:14
【问题描述】:
如何在 Android 中更改 AlertDialog 中按钮的颜色?
【问题讨论】:
标签: android button colors dialog alert
如何在 Android 中更改 AlertDialog 中按钮的颜色?
【问题讨论】:
标签: android button colors dialog alert
您指的是中性、积极和消极按钮吗?还是布局中包含的按钮?
如果您指的是前者,那么可以。查看Custom Button section in this tutorial。您基本上需要一个 XML 文件,该文件将告诉您的按钮用于每个状态更改的可绘制/颜色。然后,您可以将此 XML 文件设置为按钮的背景。
【讨论】:
不,您不能更改警报框默认按钮的颜色、图像或背景。 对于自定义,您需要让您在这样的自定义对话框中。
public class TryAgainAlert extends Dialog implements OnClickListener
{
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
Intent i = new Intent(getApplicationContext(), MainMenu.class);
finish();
startActivity(i);
return true;
}
return super.onKeyDown(keyCode, event);
}
TextView scores;
Button tryagain,mainmenu,submit;
public TryAgainAlert(Context context) {
super(context);
setContentView(R.layout.tryagainalert);
scores=(TextView)findViewById(R.id.text);
tryagain= (Button) findViewById(R.id.trya);
mainmenu= (Button) findViewById(R.id.submitscore);
submit= (Button) findViewById(R.id.mainmenu);
}
@Override
public void onClick(View v) {
if(v == tryagain)
{
else if (v==mainmenu)
{
}
else if (v == submit)
{
}
}
}
您可以对 XML 文件做任何您想做的事情。 我希望它会有所帮助。 谢谢
【讨论】:
这就是我的做法。
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));
}
我找到了可绘制的here
【讨论】:
这里有一些例子:
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);
【讨论】:
由于现在大多数人可能都在使用DialogFragment,所以我遇到了一些问题,并通过几个 SO 答案点击了我的方式来解决这些问题。让我发布我当前的解决方案。
我最终使用自定义可绘制对象设置按钮背景,正如已经多次建议的那样。但是,这在DialogFragment 的onCreateDialog 方法中尚无法实现。您可以这样做,例如在onStart() 中,或者(这是我更喜欢的)在对话框的onShow-listener 中!但请记住,您需要在更改后使按钮无效。
至于边距:只需删除 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>
【讨论】:
我认为有些开发人员希望扩展 AlertDialog 类并使用类定义定义按钮颜色。为此,您可以使用以下代码:
class MyDialog extends AlertDialog {
public MyDialog(final Context context) {
super(context);
setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button negativeButton = getButton(DialogInterface.BUTTON_NEGATIVE);
Button positiveButton = getButton(DialogInterface.BUTTON_POSITIVE);
negativeButton.setBackgroundColor(Color.GREEN);
positiveButton.setBackgroundColor(Color.RED);
}
});
}
}
【讨论】:
我已经完成了这段代码,它可能会对你有所帮助:
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);
【讨论】:
更改 AlertDailog 的按钮颜色
代码:
// Initialize AlertDialog & AlertDialog Builder
AlertDialog.Builder builder = new AlertDialog.Builder(YourActivity.this);
builder.setTitle(R.String.AlertDialogTitle);
...........
.........
//Build your AlertDialog
AlertDialog Demo_alertDialog= builder.create();
Demo_alertDialog.show();
//For Positive Button:
Button b_pos;
b_pos=Demo_alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
if(b_pos!=null){
b_pos.setTextColor(getResources().getColor(R.color.YourColor));
}
//For Neutral Button:
Button b_neu;
b_neu=Demo_alertDialog.getButton(DialogInterface.BUTTON_NEUTRAL);
if(b_neu!=null){
b_neu.setTextColor(getResources().getColor(R.color.YourColor));
}
//For Negative Button:
Button b_neg;
b_neg=Demo_alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
if(b_neg!=null){
b_neg.setTextColor(getResources().getColor(R.color.YourColor));
}
【讨论】:
也可以使用 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>
【讨论】:
如果您使用的是 DialogFragment ( android.app.DialogFragment ),那么您可以覆盖 onStart 方法来获取所有按钮(正、负和中性)的句柄。
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View eventEditDialogView = View.inflate(this.getActivity(), R.layout.event_edit_dialog,
null);
builder.setTitle(getLocalizedString("edit_event"))
.setView(eventEditDialogView)
.setPositiveButton(getLocalizedString("all_events"), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton(getLocalizedString("this_event"), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
return builder.create();
}
@Override
public void onStart() {
super.onStart();
Button positive = ((AlertDialog) getDialog()).getButton(AlertDialog.BUTTON_POSITIVE);
positive.setTextColor(Color.BLACK);
positive.setBackgroundColor(getResources().getColor(R.color.GrayBGColor));
}
上述所有解决方案都适用于在同一活动或片段上创建的 AlertDialog 或 Dialog,但不适用于单独创建的 DialogFragment。
【讨论】:
我想用主题而不是额外的代码来解决这个问题,因为在 styles.xml 中包含所有与样式相关的东西对我来说感觉更干净。我所做的是基于 Arade 的回答和this other question:
<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();
【讨论】:
我们可以使用 Style 更改警报对话框按钮的文本颜色。
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>
【讨论】:
//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"));
}
【讨论】:
这是对我有用的完美解决方案:
AlertDialog.Builder alertDialogBuilder
= new AlertDialog.Builder(DashboardActivity.this);
alertDialogBuilder.setTitle("");
alertDialogBuilder.setMessage("Are you sure you want to Logout?");
alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
preferenceManager.logout();
Intent intent = new Intent(DashboardActivity.this,
LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
});
alertDialogBuilder.setNegativeButton("Cancel", null);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
Button btnOk = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
Button btnCancel = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
if (btnOk != null && btnCancel != null) {
btnOk.setTextColor(getResources().getColor(R.color.colorGreenButton));
btnCancel.setTextColor(getResources().getColor(R.color.colorGreenButton));
} else {
Log.i(TAG, "LogOut: Buttons of Dialog are null");
}
【讨论】:
这是你的做法:
// Initializing a new alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.message);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
doAction();
}
});
builder.setNegativeButton(R.string.cancel, null);
// Create the alert dialog and change Buttons colour
AlertDialog dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface arg0) {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.red));
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.blue));
//dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(getResources().getColor(R.color.black));
}
});
dialog.show();
【讨论】:
有两种方法:
val builder = AlertDialog.Builder(activity!!)
...
val dialog = builder.create()
.apply {
setOnShowListener {
getButton(Dialog.BUTTON_NEGATIVE)?.setTextColor(...)
}
}
<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()
【讨论】:
只需将字符串设为 Spannable 并将其传递给 setPositveButton 或否定按钮 像这样
val n=getString(R.string.reject).toSpannable() n.setSpan(ForegroundColorSpan(Color.RED),0,6,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
n.setNegativeButton(n)
【讨论】:
也许有人已经这样回答了,但在我看来,我没有找到,所以我更喜欢这个效果很好的答案。记住 setTextColor 应该在 dialog.show() 之后应用,否则我
dialog.show(); //Only after .show() was called
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(neededColor);
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(neededColor);
【讨论】: