Imágenes de los botones de AlertDialog
¿Es posible añadir elementos extraíbles a los botones positivo , negativo y neutro de un AlertDialog? Si es así, ¿cómo?
- Indent bullet list en TextView
- Android: Creación de un diseño principal y ampliación para mantener un aspecto idéntico en todas las actividades de la aplicación
- Fuentes centrales de imágenes de NinePatch?
- Cambiar texto del texto ListView de Android en la selección
- AutoCompleteTextView siempre mantiene el foco
- Herramienta para diseñar Layout para Android -apps en línea?
- Mostrar diálogo Sí / No antes de salir de la aplicación mediante el botón Atrás
- Cómo compilar código de ejemplo
- Facebook Slide menu-slide a la derecha en android?
- ¿Hay alguna forma de que los elementos de la interfaz de usuario se superpongan ligeramente (uno encima del otro) sin usar diseños absolutos?
- La ficha Diseño gráfico no aparece para algunos archivos de diseño en Eclipse
- Barra de acciones: práctica recomendada para versiones anteriores de Android
- Actividad de Android sin GUI
Dado que onPrepareDialog
está obsoleto, puede usar el onShowListener
.
También debe establecer los límites Drawable o se colocará a la izquierda.
Salida del código a continuación
public class MyDialog extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final AlertDialog dialog = new AlertDialog.Builder(getActivity()) .setTitle("My Dialog") .setNegativeButton("Cancel", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }).setPositiveButton("Play", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }).create(); dialog.setOnShowListener(new OnShowListener() { @Override public void onShow(DialogInterface dialogInterface) { Button button = dialog.getButton(AlertDialog.BUTTON_POSITIVE); // if you do the following it will be left aligned, doesn't look // correct // button.setCompoundDrawablesWithIntrinsicBounds(android.R.drawable.ic_media_play, // 0, 0, 0); Drawable drawable = getActivity().getResources().getDrawable( android.R.drawable.ic_media_play); // set the bounds to place the drawable a bit right drawable.setBounds((int) (drawable.getIntrinsicWidth() * 0.5), 0, (int) (drawable.getIntrinsicWidth() * 1.5), drawable.getIntrinsicHeight()); button.setCompoundDrawables(drawable, null, null, null); // could modify the placement more here if desired // button.setCompoundDrawablePadding(); } }); return dialog; } }
Después de haber creado el AlertDialog
en onCreateDialog
puede utilizar el siguiente código en onPrepareDialog
para agregar una imagen al botón positivo:
@Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); AlertDialog alertDialog = (AlertDialog)dialog; Button button = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE); button.setCompoundDrawablesWithIntrinsicBounds(this.getResources().getDrawable( R.drawable.icon), null, null, null); }
Intentar agregar el drawable al botón en el método onCreateDialog
no parece funcionar.
Esto puede hacerse obteniendo una referencia al botón mediante el método getButton ():
alert.show(); Button email = alert.getButton(AlertDialog.BUTTON_NEUTRAL); email.setBackgroundResource(R.drawable.email);
Tenga en cuenta que debe utilizar getButton () DESPUÉS de llamar al método show (), de lo contrario obtendrá una excepción NullPointerException.
Usted no puede agregar botones en el onCreateDialog y DEBE hacerlo en el onPrepareDialog porque AlertDialog se manejan de una manera muy especial por android:
En realidad no tiene una referencia al diálogo real cuando utiliza el diálogo de alerta, el objeto que obtiene mediante AlertDialog.Builder.create () es sólo una cara a un controlador interno.
Y antes de crear es realmente llamado, no hay tal controlador en el jvm. Sólo la fachada. Por lo tanto, hasta que se llama a este método (al final de onCreateDialog si deja que su actividad administre sus propios cuadros de diálogo), el controlador real no existe y los botones reales no lo hacen.
Nuevo comentarista SOF, Stéphane
Como dijo @ aaronvargas, utilice onShowListener
. Voy a mejorar su respuesta un poco, ya que para los dispositivos más antiguos / más pequeños de la imagen se superpone el texto. Aquí está el código onShow
:
@Override public void onShow(DialogInterface dialogInterface) { Button button = dialog.getButton(AlertDialog.BUTTON_POSITIVE); button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.your_img, 0, 0, 0); Utils.centerImageAndTextInButton(button); }
Esta es una función de utilidad para centrar una imagen izquierda y el texto dentro de un Button
:
public static void centerImageAndTextInButton(Button button) { Rect textBounds = new Rect(); //Get text bounds CharSequence text = button.getText(); if (text != null && text.length() > 0) { TextPaint textPaint = button.getPaint(); textPaint.getTextBounds(text.toString(), 0, text.length(), textBounds); } //Set left drawable bounds Drawable leftDrawable = button.getCompoundDrawables()[0]; if (leftDrawable != null) { Rect leftBounds = leftDrawable.copyBounds(); int width = button.getWidth() - (button.getPaddingLeft() + button.getPaddingRight()); int leftOffset = (width - (textBounds.width() + leftBounds.width()) - button.getCompoundDrawablePadding()) / 2 - button.getCompoundDrawablePadding(); leftBounds.offset(leftOffset, 0); leftDrawable.setBounds(leftBounds); } }
Esta última función utiliza el ancho del Button
para realizar el cálculo, por lo que debe comprobar que está llamando a este lugar en el lugar correcto. Es decir, el ancho debe ser distinto de cero. En este caso, llamarlo desde onShow
es el lugar correcto :).
1.Primero cree un nuevo archivo de diseño para almacenar los botones de imagen: new_layout.xml;
<?xml version="1.0" encoding="UTF-8" ?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_margin="15dp" android:gravity="center_horizontal" android:background = "#FFFFFF" android:orientation="horizontal"> <!-- game button --> <ImageButton android:id="@+id/game" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_margin="5dp" android:layout_gravity="bottom" android:background = "#00ffffff" android:src="@drawable/game"/> <!-- browser button --> <ImageButton android:id="@+id/browser" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_margin="5dp" android:layout_gravity="bottom" android:background = "#00ffffff" android:src="@drawable/browser"/> <!-- email button --> <ImageButton android:id="@+id/email" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_margin="5dp" android:layout_gravity="bottom" android:background = "#00ffffff" android:src="@drawable/email"/> </LinearLayout>
2.add el código abajo a donde usted quiere que el diálogo muestre:
final AlertDialog alertDialog = new AlertDialog.Builder(TalkerActivity.this).create(); alertDialog.show(); Window win = alertDialog.getWindow(); win.setContentView(R.layout.new_layout); //Game ImageButton game_btn = (ImageButton)win.findViewById(R.id.game); game_btn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub } }); //Browser ImageButton browser_btn = (ImageButton)win.findViewById(R.id.browser); browser_btn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub } }); //Email ImageButton email_btn = (ImageButton)win.findViewById(R.id.email); email_btn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub } });
Enlace: http://blog.csdn.net/willproud/article/details/9191971
- Cómo configurar android: layout_alignParentLeft atributo a imageview en el código?
- Instalar OpenGL ES y código de compilación para android