2010-11-04 32 views
30

¿Cómo puedo cambiar el color de los botones en un AlertDialog en Android?Cambiar el color del botón en AlertDialog

+0

ver en esto [Android diálogo con la costumbre de color y diseño] (http://stackoverflow.com/a/30388711/782535) . –

Respuesta

-1

¿Te refieres a los botones neutral, positivo y negativo? ¿O a los botones que incluiste en el diseño?

Si te refieres a la primera, entonces sí puedes. Consulte el Custom Button section in this tutorial. Básicamente, necesita un archivo XML que indique a su botón qué dibuja/color usar para cada cambio de estado. Luego puede establecer este archivo XML como fondo de su botón.

+0

No budy, ya lo hice. Pero tengo que cambiar el fondo del botón positivo, neutral y negativo. . . –

+0

Hola, ¿lograste arreglar este problema? – jonney

0

no, no se puede cambiar el color o las imágenes o el fondo de los botones predeterminados de los cuadros de alerta. Para la personalización necesitará hacer un cuadro de diálogo personalizado como este.

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) 
     { 

     } 
    } 

} 

puede hacer lo que quiera con el archivo XML. Espero que ayude. Gracias

60

Así es como lo hice.

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)); 
} 

encuentro el dibujable here

+2

hola, también estoy aplicando la imagen de BG del botón de esta manera. pero si aplico la imagen, obtengo un margen no deseado en la parte inferior del botón. si uso el color BG, estoy funcionando bien. revisé la imagen del botón. esta bien. así que puedes sugerir alguna solución para esto. – Raj

+0

@Raj ¿Encontró alguna solución para estos márgenes no deseados? – Deepak

+0

@Deepak: aún no se ha encontrado ninguna solución. si encontraste alguno, házmelo saber. – Raj

7

Aquí está un cierto ejemplo:

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); 
18

Como la mayoría de la gente probablemente está utilizando un DialogFragment por ahora me encontré con algunos problemas y hacer clic mi camino a través de varios SO respuestas para resolver esos. Déjame publicar mi solución actual.

Terminé configurando el botón de fondo con herramientas personalizables como ya se sugirió varias veces. Sin embargo, esto aún no era posible en el onCreateDialog -metodo de DialogFragment. Puedes hacer esto, p. en onStart(), o (que es lo que preferí) en el onShow -listener del diálogo! Sin embargo, tenga en cuenta que debe invalidar sus botones luego de los cambios.

En cuanto a los márgenes: simplemente elimine el relleno en su Drawable-XML para los botones.

#onCreateDialog en su 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; 
} 

ejemplo Disponibles en XML para un botón:

<?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> 

No se olvide de definir sus colores en el res\values\colors.xml, p.ej así (yo no quería un gradiente, por lo tanto, los colores 1 & 2 son iguales):

<?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> 
1

Creo que hay desarrolladores que desean extender la clase AlertDialog y definir los botones de colores withing definición de clase.Para tal fin se puede utilizar este código:

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); 
      } 
     }); 
    } 
} 
6

que he hecho por este código que podría ayudarle a:

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); 
0

Para cambiar el color de los botones del Código 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)); 
    } 
0

El color de los botones y otros textos también se pueden cambiar con el 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> 
0

si está utilizando DialogFragment (android.app.DialogFragment), entonces usted puede sobrescribir onStart método para obtener la manija de todos los botones (positivas, negativas y neutras).

@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)); 
} 

Todas las soluciones anteriores funcionarán con AlertDialog o diálogo creado en la misma actividad o fragmento, pero no en DialogFragment creados por separado.

3

Quería resolver esto con temas en lugar de código adicional, ya que me parece más limpio tener todo el material relacionado con el estilo en styles.xml. Lo que hice fue basada en la respuesta de Arade y this other question:

<style name="AlertDialogDanger" parent="Theme.AppCompat.Light.Dialog.Alert"> 
    <item name="colorAccent">@color/error</item> 
</style> 

Esto cambiará el color del texto del botón de cualquier diálogo de alerta se crea con el estilo AlertDialogDanger. Para ello:

new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogDanger)) 
      .setMessage("Really delete?") 
      .setPositiveButton("Delete", null) 
      .setNegativeButton("Cancel", null) 
      .create().show(); 
2

podemos cambiar el botón de diálogo de alerta color del texto usando estilo.

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> 
0
//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")); 
} 
Cuestiones relacionadas