Configurar el tamaño de un DialogFragment
He estado intentando muchos comandos para configurar el tamaño de mi DialogFragment
. Sólo contiene un selector de color, por lo que he eliminado el fondo y el título del diálogo:
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); getDialog().getWindow().setBackgroundDrawable( new ColorDrawable(android.graphics.Color.TRANSPARENT));
Sin embargo también quiero colocar el diálogo donde quiero y es problemático. Yo suelo:
- Cómo mostrar un menú desplegable como la cabeza de chat de libro de cara en android
- DialogFragment con un diseño personalizado causa un bloqueo en mi aplicación
- Cómo reemplazar un DialogFragment por otro DialogFragment?
- Disposición de esquina redonda de Android en el cuadro de diálogo
- Android: Orden de DialogFragments cambiando después de la actividad se reanuda
WindowManager.LayoutParams params = getDialog().getWindow().getAttributes(); params.width = LayoutParams.WRAP_CONTENT; params.height = LayoutParams.WRAP_CONTENT; params.gravity = Gravity.LEFT; getDialog().getWindow().setAttributes(params);
Pero un obstáculo (grande) sigue siendo: aunque mi panel de diálogo es invisible, todavía tiene un cierto tamaño, y limita las posiciones de mi diálogo. LayoutParams.WRAP_CONTENT
está aquí para limitar el tamaño de este panel a mi selector de color, pero por alguna razón no funciona.
¿Alguien ha sido capaz de hacer algo similar?
- Destruye DialogFragment en onCreateDialog ()
- Cómo mostrar un DialogFragment de un controlador
- Android: FragmentTransaction ocultar no funciona para DialogFragment
- Permitir el toque externo para DialogFragment
- Android DialogFragment no descarta
- Comunicación entre fragmentos / cuadros de diálogo en android
- DialogFragment pantalla completa muestra relleno en los lados
- GetLocationOnScreen devuelve la posición antigua después de la rotación
Me encontré con una pregunta similar que es que no se puede establecer la anchura del cuadro de diálogo de una altura en el código, después de varios intento, encontré una solución;
Aquí hay pasos para custom DialogFragment:
1. infla la vista personalizada desde xml en el método
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); getDialog().setCanceledOnTouchOutside(true); View view = inflater.inflate(R.layout.XXX, container, false); //TODO:findViewById, etc return view; }
2.set el ancho de su cuadro de diálogo una altura en onResume (), remrember en onResume () / onStart (), parece que no funcionó en otro método
public void onResume() { super.onResume(); Window window = getDialog().getWindow(); window.setLayout(width, height); window.setGravity(Gravity.CENTER); //TODO: }
Después de algunas pruebas y errores, he encontrado la solución.
Aquí está la implementación de mi clase DialogFragment:
public class ColorDialogFragment extends SherlockDialogFragment { public ColorDialogFragment() { //You need to provide a default constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.dialog_color_picker, container); // R.layout.dialog_color_picker is the custom layout of my dialog WindowManager.LayoutParams wmlp = getDialog().getWindow().getAttributes(); wmlp.gravity = Gravity.LEFT; return view; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NO_FRAME, R.style.colorPickerStyle); // this setStyle is VERY important. // STYLE_NO_FRAME means that I will provide my own layout and style for the whole dialog // so for example the size of the default dialog will not get in my way // the style extends the default one. see bellow. } }
R.style.colorPickerStyle corresponde a:
<style name="colorPickerStyle" parent="Theme.Sherlock.Light.Dialog"> <item name="android:backgroundDimEnabled">false</item> <item name="android:cacheColorHint">@android:color/transparent</item> <item name="android:windowBackground">@android:color/transparent</item> </style>
Simplemente extender un estilo de diálogo predeterminado con mis necesidades.
Por último, puede invocar este diálogo con:
private void showDialog() { ColorDialogFragment newFragment = new ColorDialogFragment(); newFragment.show(getSupportFragmentManager(), "colorPicker"); }
Para mi caso de uso, quería que el DialogFragment coincidiera con el tamaño de una lista de elementos. La vista de fragmento es un RecyclerView en un diseño llamado fragment_sound_picker
. He añadido un envoltorio RelativeLayout alrededor del RecyclerView.
Ya había establecido la altura de la vista individual del elemento de lista con R.attr.listItemPreferredHeight
, en un diseño llamado item_sound_choice
.
El DialogFragment obtiene una instancia de LayoutParams desde el RecyclerView de la vista inflada, ajusta la altura de LayoutParams a un múltiplo de la longitud de la lista y aplica el LayoutParams modificado a la vista primaria inflado.
El resultado es que el DialogFragment envuelve perfectamente la lista corta de opciones. Incluye el título de la ventana y los botones Cancelar / Aceptar.
Aquí está la configuración en el DialogFragment:
// SoundPicker.java // extends DialogFragment @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(getActivity().getString(R.string.txt_sound_picker_dialog_title)); LayoutInflater layoutInflater = LayoutInflater.from(getActivity()); View view = layoutInflater.inflate(R.layout.fragment_sound_picker, null); RecyclerView rv = (RecyclerView) view.findViewById(R.id.rv_sound_list); rv.setLayoutManager(new LinearLayoutManager(getActivity())); SoundPickerAdapter soundPickerAdapter = new SoundPickerAdapter(getActivity().getApplicationContext(), this, selectedSound); List<SoundItem> items = getArguments().getParcelableArrayList(SOUND_ITEMS); soundPickerAdapter.setSoundItems(items); soundPickerAdapter.setRecyclerView(rv); rv.setAdapter(soundPickerAdapter); // Here's the LayoutParams setup ViewGroup.LayoutParams layoutParams = rv.getLayoutParams(); layoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT; layoutParams.height = getListItemHeight() * (items.size() + 1); view.setLayoutParams(layoutParams); builder.setView(view); builder.setCancelable(true); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { // ... }); builder.setPositiveButton(R.string.txt_ok, new DialogInterface.OnClickListener() { // ... }); return builder.create(); } @Override public void onResume() { Window window = getDialog().getWindow(); window.setLayout(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); super.onResume(); } private int getListItemHeight() { TypedValue typedValue = new TypedValue(); getActivity().getTheme().resolveAttribute(R.attr.listPreferredItemHeight, typedValue, true); DisplayMetrics metrics = new android.util.DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics); return (int) typedValue.getDimension(metrics); }
Aquí está fragment_sound_picker
:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.RecyclerView android:id="@+id/rv_sound_list" android:layout_width="match_parent" android:layout_height="wrap_content" /> </RelativeLayout>
Utilice este código para cambiar el tamaño de Dialog Fragment android
public void onResume() { super.onResume(); super.onResume(); Window window = getDialog().getWindow(); window.setLayout(250, 100); window.setGravity(Gravity.RIGHT); }
- No se puede encontrar un SDK Android compatible para la compilación al ejecutar `plataforma tns add android`
- Cómo cargar una imagen en el servidor de análisis utilizando analizar api en android