Establecer un ancho máximo en un grupo de vistas

¿Cómo establezco el ancho máximo de un grupo de vistas? Estoy utilizando una actividad Theme.Dialog , sin embargo, esto no se ve tan bien cuando se cambia el tamaño a las pantallas más grandes, también es una especie de peso ligero y no quiero que ocupe toda la pantalla.

Intenté esta sugerencia sin éxito. Además, no hay ninguna propiedad android:maxWidth como algunas vistas.

¿Hay una manera de restringir la raíz LinearLayout para que sea sólo (por ejemplo) 640 dip? Estoy dispuesto a cambiar a otro ViewGroup para esto.

¿Alguna sugerencia?

Una opción que es lo que hice fue extender LinearLayout y anular la función onMeasure. Por ejemplo:

 public class BoundedLinearLayout extends LinearLayout { private final int mBoundedWidth; private final int mBoundedHeight; public BoundedLinearLayout(Context context) { super(context); mBoundedWidth = 0; mBoundedHeight = 0; } public BoundedLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BoundedView); mBoundedWidth = a.getDimensionPixelSize(R.styleable.BoundedView_bounded_width, 0); mBoundedHeight = a.getDimensionPixelSize(R.styleable.BoundedView_bounded_height, 0); a.recycle(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // Adjust width as necessary int measuredWidth = MeasureSpec.getSize(widthMeasureSpec); if(mBoundedWidth > 0 && mBoundedWidth < measuredWidth) { int measureMode = MeasureSpec.getMode(widthMeasureSpec); widthMeasureSpec = MeasureSpec.makeMeasureSpec(mBoundedWidth, measureMode); } // Adjust height as necessary int measuredHeight = MeasureSpec.getSize(heightMeasureSpec); if(mBoundedHeight > 0 && mBoundedHeight < measuredHeight) { int measureMode = MeasureSpec.getMode(heightMeasureSpec); heightMeasureSpec = MeasureSpec.makeMeasureSpec(mBoundedHeight, measureMode); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } 

A continuación, XML utilizaría la clase personalizada:

 <com.yourpackage.BoundedLinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" app:bounded_width="900dp"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" /> </com.youpackage.BoundedLinearLayout> 

Y la entrada del archivo attr.xml

 <declare-styleable name="BoundedView"> <attr name="bounded_width" format="dimension" /> <attr name="bounded_height" format="dimension" /> </declare-styleable> 

EDIT: Este es el código actual que estoy usando ahora. Esto todavía no está completo, pero funciona en la mayoría de los casos.

Sobre la base de la respuesta original de Chase (+1) haría un par de cambios (se describe a continuación).

  1. Tendría el ancho máximo establecido a través de un atributo personalizado (xml debajo del código)

  2. Llamaré super.measure() primero y después haré la Math.min(*) . Utilizando el código de respuestas original, podemos encontrar problemas cuando el tamaño entrante establecido en MeasureSpec es LayoutParams.WRAP_CONTENT o LayoutParams.FILL_PARENT . Como estas constantes válidas tienen valores de -2 y -1 respectivly, el Math.min(*) original Math.min(*) vuelve inútil ya que preservará estos vales sobre el tamaño máximo y dirá que el WRAP_CONTENT medido es más grande que nuestro tamaño máximo que esta verificación no Atrapalo. Me imagino que el OP estaba pensando en dims exacta sólo (para lo que funciona muy bien)

     public class MaxWidthLinearLayout extends LinearLayout { private int mMaxWidth = Integer.MAX_VALUE; public MaxWidthLinearLayout(Context context) { super(context); } public MaxWidthLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.MaxWidthLinearLayout); mMaxWidth = a.getDimensionPixelSize(R.styleable.MaxWidthLinearLayout_maxWidth, Integer.MAX_VALUE); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //get measured height if(getMeasuredWidth() > mMaxWidth){ setMeasuredDimension(mMaxWidth, getMeasuredHeight()); } } } 

Y el xml attr

  <!-- MaxWidthLinearLayout --> <declare-styleable name="MaxWidthLinearLayout"> <attr name="maxWidth" format="dimension" /> </declare-styleable> 

Aquí está el mejor código para la respuesta de Dori.

En el método onMeasure , si llama a super.onMeasure(widthMeasureSpec, heightMeasureSpec); Primero en el método, entonces no se cambiará el ancho de todos los objetos en el diseño. Porque se inicializaron antes de establecer el ancho de diseño (padre).

 public class MaxWidthLinearLayout extends LinearLayout { private final int mMaxWidth; public MaxWidthLinearLayout(Context context) { super(context); mMaxWidth = 0; } public MaxWidthLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.MaxWidthLinearLayout); mMaxWidth = a.getDimensionPixelSize(R.styleable.MaxWidthLinearLayout_maxWidth, Integer.MAX_VALUE); a.recycle(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measuredWidth = MeasureSpec.getSize(widthMeasureSpec); if (mMaxWidth > 0 && mMaxWidth < measuredWidth) { int measureMode = MeasureSpec.getMode(widthMeasureSpec); widthMeasureSpec = MeasureSpec.makeMeasureSpec(mMaxWidth, measureMode); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } 

Y aquí hay un enlace para el uso de xml attr:
http://kevindion.com/2011/01/custom-xml-attributes-for-android-widgets/

Gracias por esta pregunta y respuestas. Su respuesta me ha ayudado mucho, y espero que ayude a otra persona en el futuro también.

Ahora android.support.constraint.ConstraintLayout hace más fácil. Simplemente envuelva su vista (de cualquier tipo) con ConstraintLayout y establezca los atributos siguientes en la vista:

 android:layout_width="0dp" app:layout_constraintWidth_default="spread" app:layout_constraintWidth_max="640dp" 

http://tools.android.com/recent/constraintlayoutbeta5isnowavailable

Agregue una capa de Layout externo o de grupo de vista a su archivo de disposición actual. La altura y el ancho de este Layout serán la altura / ancho máximo. Ahora su disposición interna se puede fijar para envolver el contenido y es limitada por el diseño exterior. P.ej:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!-- OuterLayout to set Max Height and Width -- Add this ViewGroup to your layout File --> <LinearLayout android:id="@+id/outerLayout" android:layout_width="650dp" android:layout_height="650dp" android:orientation="vertical" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > </LinearLayout> </LinearLayout> </LinearLayout> 

Aquí está una respuesta simple,

El ancho / la altura parecen siempre tener que ser fijados juntos. Esto está funcionando en mi opinión.

  <Button android:text="Center" android:layout_width="100dp" android:layout_height="fill_parent" android:id="@+id/selectionCenterButton" android:minWidth="50dp" android:minHeight="50dp" android:maxWidth="100dp" android:maxHeight="50dp" android:layout_weight="1" /> 

El padre del botón está configurado para ajustar el contenido, por lo que se reduce, pero hasta un máximo de 400 de ancho (4 botones).

  • Cómo deshabilitar el colapso de un ExpandableListView?
  • Android 3.0, Vista previa de widgets
  • El fondo de la vista ampliable se vuelve negro cuando se amplía
  • ListView expandir animación para elementos sólo funciona después del segundo clic
  • Vista vacía en el adaptador de lista expandible
  • Cómo pasar un valor de cadena a webView de una actividad
  • Cómo obtener el estado de la casilla de verificación en el listview expandible en android
  • Custom ExpandableListview Android
  • Presentar contenido html como "páginas dinámicas"
  • Cómo actualizar la vista de la vista de fila de elementos anteriores de la vista de reciclaje
  • OnTouchListener en vista invisible
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.