studio programacion para móviles libro edición desarrollo desarrollar curso aprende aplicaciones android dialog imageview alertdialog

android - programacion - Mostrar AlertDialog con ImageView sin ningún tipo de relleno



manual de programacion android pdf (8)

Agrego estos atributos a mi ImageView.

<ImageView (...) android:adjustViewBounds="true" />

¡Funcionó!

EDITAR - SOLUCIÓN:

Terminé encontrando una manera de resolver este problema. Debido a que el cambio manual de la altura de ImageView elimina el relleno adicional, terminé encontrando las dimensiones de la imagen original y las aplico a ImageView una vez que se pueden calcular las dimensiones de ImageView. Aquí esta el resultado final:

Este es el código de trabajo final:

AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setPositiveButton("Get Pro", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setNegativeButton("No thanks", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); final AlertDialog dialog = builder.create(); LayoutInflater inflater = getLayoutInflater(); View dialogLayout = inflater.inflate(R.layout.go_pro_dialog_layout, null); dialog.setView(dialogLayout); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.show(); dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface d) { ImageView image = (ImageView) dialog.findViewById(R.id.goProDialogImage); Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.whygoprodialogimage); float imageWidthInPX = (float)image.getWidth(); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Math.round(imageWidthInPX), Math.round(imageWidthInPX * (float)icon.getHeight() / (float)icon.getWidth())); image.setLayoutParams(layoutParams); } });

Y el XML:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView android:id="@+id/goProDialogImage" android:layout_width="wrap_content" android:layout_height="350dp" android:src="@drawable/whygoprodialogimage"/> </LinearLayout>

PREGUNTA ORIGINAL:

Mi objetivo es tener un AlertDialog que tenga un ImageView que ocupe todo el diálogo, conservando sus dimensiones, más dos botones. Al implementarlo a través de métodos estándar, se parece a lo siguiente:

Estoy tratando de eliminar ese relleno por encima y por debajo de él. Aquí está el código de cómo está configurado:

Diseño:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/goProDialogImage" android:layout_width="match_parent" android:layout_height="wrap_content" android:src="@drawable/whygoprodialogimage"/> </LinearLayout>

Código:

AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setPositiveButton("Get Pro", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setNegativeButton("No thanks", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog dialog = builder.create(); LayoutInflater inflater = getLayoutInflater(); View dialogLayout = inflater.inflate(R.layout.go_pro_dialog_layout, null); dialog.setView(dialogLayout); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.show();

Después de ver esta respuesta de StackOverflow , intenté implementar esa solución porque su problema parecía similar, pero aunque está más cerca de lo que quiero ahora, el resultado es el siguiente:

Así se eliminó el relleno pero la imagen se ve aplastada. Aquí está el código para esta posible implementación de la solución:

// Get screen size Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int screenWidth = size.x; int screenHeight = size.y; // Get target image size Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.whygoprodialogimage); int bitmapHeight = bitmap.getHeight(); int bitmapWidth = bitmap.getWidth(); // Scale the image down to fit perfectly into the screen // The value (250 in this case) must be adjusted for phone/tables displays while(bitmapHeight > (screenHeight - 250) || bitmapWidth > (screenWidth - 250)) { bitmapHeight = bitmapHeight / 2; bitmapWidth = bitmapWidth / 2; } // Create resized bitmap image BitmapDrawable resizedDialogImage = new BitmapDrawable(context.getResources(), Bitmap.createScaledBitmap(bitmap, bitmapWidth, bitmapHeight, false)); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setPositiveButton("Get Pro", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setNegativeButton("No thanks", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog dialog = builder.create(); LayoutInflater inflater = getLayoutInflater(); View dialogLayout = inflater.inflate(R.layout.go_pro_dialog_layout, null); dialog.setView(dialogLayout); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // Without this line there is a very small border around the image (1px) dialog.getWindow().setBackgroundDrawable(null); dialog.show(); ImageView image = (ImageView) dialog.findViewById(R.id.goProDialogImage); image.setBackground(resizedDialogImage);

¿Qué es lo que está haciendo que la imagen se vea aplastada? Se puede decir que se eliminó el relleno adicional, pero se cambiaron las dimensiones de la imagen.


Aquí hay algunas cosas que puedes probar. Intenta variaciones de esto para ver si corrige la relación de visualización. Description

imageView.setScaleType(ScaleType.FIT_CENTER);

o posiblemente el ajuste manual del tamaño de ImageView manualmente ayudará.

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(bitmapWidth, bitmapHeight); image.setLayoutParams(layoutParams);

Si no, hay algunas otras formas, estas fueron solo las primeras que me vinieron a la mente.


Configure el atributo LinearLayout de su vista, es decir, android:layout_height="match_parent" . Espero que funcione.


El panel personalizado de un AlertDialog tiene un relleno superior e inferior de 5dp. Puede anular estos usando:

reemplazar esta linea

dialog.setView(dialogLayout);

dentro

dialog.setView(dialogLayout, 0, 0, 0, 0);

Para más información consultar estos enlaces,

No se puede obtener el AlertDialog personalizado adecuado


No estoy seguro, pero creo que es el tipo de diálogo que está mostrando el que agrega el relleno. Este tipo de diálogo no oculta toda la actividad. Lo que utilizo para ocultar toda la actividad es:

/** * Show the overlay using the WindowManager class. * @param overlay The overlay that needs to be shown. */ public void showOverlay(View overlay) { WindowManager.LayoutParams params = new WindowManager.LayoutParams( WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_FULLSCREEN, PixelFormat.TRANSLUCENT); getWindowManager().addView(overlay, params); }

Probablemente puedas encontrar una opción que haga lo que necesitas. Sin embargo, deberá crear un diseño que contenga los botones y la imagen si desea utilizar el método anterior.

Verifique las opciones: http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html


Puede ser tarde, pero creo que la configuración de android:adjustViewBounds = "true" en ImageView podría ayudar. Además, generalmente establezco android:scaleType = "centerInside" o android:scaleType = "centerCrop"


Tanto el diseño como la vista de imagen tienen layout_width="match_parent" . Esto le indica a la vista (ya sea el diseño o la vista de imagen) que se extienda para que llene el contenedor principal. Intente cambiar esta propiedad a wrap_content . Puede encontrar una explicación detallada de la propiedad en la documentación oficial, here

Establecerlo en wrap_content debería tener el mismo efecto que en la altura: debería ser lo suficientemente ancho como para dibujar el contenido (la imagen en este caso) en lugar de fijar su tamaño (al del padre / contenedor)


Terminé encontrando una manera de resolver este problema. Debido a que el cambio manual de la altura de ImageView elimina el relleno adicional, terminé encontrando las dimensiones de la imagen original y las aplico a ImageView una vez que se pueden calcular las dimensiones de ImageView. Aquí esta el resultado final:

Este es el código de trabajo final:

AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setPositiveButton("Get Pro", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setNegativeButton("No thanks", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); final AlertDialog dialog = builder.create(); LayoutInflater inflater = getLayoutInflater(); View dialogLayout = inflater.inflate(R.layout.go_pro_dialog_layout, null); dialog.setView(dialogLayout); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.show(); dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface d) { ImageView image = (ImageView) dialog.findViewById(R.id.goProDialogImage); Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.whygoprodialogimage); float imageWidthInPX = (float)image.getWidth(); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Math.round(imageWidthInPX), Math.round(imageWidthInPX * (float)icon.getHeight() / (float)icon.getWidth())); image.setLayoutParams(layoutParams); } });

Y el XML:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView android:id="@+id/goProDialogImage" android:layout_width="wrap_content" android:layout_height="350dp" android:src="@drawable/whygoprodialogimage"/> </LinearLayout>