Как я могу изменить цвет кнопки (ов) в AlertDialog
на Android?Изменить цвет кнопки в AlertDialog
ответ
Вы имеете в виду нейтральные, положительные и отрицательные кнопки? Или кнопками, которые вы включили в макет?
Если вы имеете в виду первое, то да, вы можете. Проверьте Custom Button section in this tutorial. Вам в основном нужен XML-файл, который будет указывать вашей кнопке, которую можно использовать для каждого изменения состояния. Затем вы можете установить этот XML-файл в качестве фона вашей кнопки.
Без тебя, я уже сделал это. Но мне нужно изменить фон положительной, нейтральной и отрицательной кнопки. , , – 2011-04-30 07:29:34
Привет, вам удалось решить эту проблему? – jonney
Нет, вы не можете изменить цвет или изображения или фон кнопок по умолчанию для предупреждающих ящиков. Для настройки вы должны будете сделать это в настраиваемом диалоговом окне.
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
привет, я также применяю BG-изображение Button, как это только. но если я применяю Image, я получаю некоторую нежелательную маржу в нижней части кнопки. если я использую цвет BG, я отлично работаю. Я проверил изображение кнопки. это нормально. поэтому вы можете предложить какое-либо решение для этого. – Raj
@Raj вы нашли какое-либо решение для этого нежелательного поля? – Deepak
@Deepak: еще не найдено решение. если вы нашли, пожалуйста, дайте мне знать. – Raj
Вот несколько примеров:
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 ответы на них. Позвольте мне опубликовать мое текущее решение.
В конце концов я установил кнопку-фон с пользовательскими чертежами, как уже было предложено несколько раз. Однако это еще не было возможным в способе onCreateDialog
DialogFragment
. Вы можете сделать это, например. в onStart()
, или (что я предпочитаю) в onShow
-listener диалога! Имейте в виду, однако, после изменения вы должны аннулировать свои кнопки.
Что касается полей: просто удалите прокладку в вашем Drawable-XML для кнопок.
#onCreateDialog в вашем DialogFragment:
@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;
}
Drawable-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 или диалогом, созданный на тот же деятельность или фрагменте, но не на DialogFragment создается отдельно.
Я хотел решить это с помощью тем, а не дополнительного кода, так как для меня стало более чистым, чтобы иметь все элементы стиля, связанные с стилями в styles.xml. То, что я сделал, основываясь на ответ Арада и 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();
мы можем изменить цвет текста кнопки диалога оповещения с помощью стиля.
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"));
}
- 1. AlertDialog изменения положительного цвет кнопки
- 2. Изменить цвет гиперссылки в AlertDialog
- 3. Изменить флажок Цвет в AlertDialog
- 4. android, как изменить цвет фона в AlertDialog
- 5. Выбрать цвет кнопки и изменить цвет кнопки
- 6. Как изменить цвет кнопки кнопки?
- 7. AlertDialog Theme: Как изменить цвет текста товара?
- 8. изменить название цвет alertDialog ниже android 5.0
- 9. Изменить цвет нажатия кнопки в диалоговом фрагменте?
- 10. Как изменить цвет фона для предупреждения AlertDialog?
- 11. Изменить цвет кнопки UIImage
- 12. Изменить цвет кнопки onClick
- 13. Как изменить цвет кнопки?
- 14. Изменить цвет текста кнопки
- 15. Как изменить цвет кнопки?
- 16. Изменить цвет кнопки
- 17. Изменить цвет текста кнопки
- 18. Изменить цвет кнопки программно
- 19. Как изменить цвет кнопки?
- 20. Как изменить цвет кнопки
- 21. Как изменить цвет кнопки
- 22. Изменить цвет приподнятой кнопки?
- 23. Изменить цвет кнопки в Kivy
- 24. Изменить цвет кнопки в DataGridViewButtonColumn
- 25. AlertDialog стиль и цвет
- 26. Как изменить цвет, текст и цвет кнопки материала AlertDialog и ProgressDialog
- 27. Android - Изменить вид при нажатии кнопки alertdialog
- 28. Изменить цвет фона элементов в AlertDialog с setSingleChoiceItems/setItems
- 29. Как изменить цвет моей кнопки цвет
- 30. Изменить фон, текстцвет AlertDialog
Посмотрите на это [Android Диалог с пользовательским цветом и дизайном] (http://stackoverflow.com/a/30388711/782535) , –