Diseño lineal y peso en Android


Siempre he leído sobre este divertido valor de peso en las documentaciones de Android. Ahora quiero probarlo por primera vez, pero no está funcionando en absoluto.

Según lo entiendo de la documentación esta disposición:

  <LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal">

     <Button
        android:text="Register"
        android:id="@+id/register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dip"
        weight="1" />

     <Button
        android:text="Not this time"
        android:id="@+id/cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dip"
        weight="1" />

  </LinearLayout>

Debe crear dos botones que estén alineados horizontalmente y compartan el espacio por igual. El problema es que los dos botones no crecen para llenar el espacio.

Me gustaría que los botones crezcan y llenen toda la línea. Si ambos botones están configurados para coincidir con el padre solo se muestra el primer botón y llena toda la línea.

Author: Janusz, 2010-04-23

18 answers

No está configurando la propiedad layout_weight. Su código dice weight="1" y debe decir android:layout_weight="1".

 141
Author: JeremyFromEarth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-13 16:14:02

3 cosas para recordar:

  • establezca el android: layout_width de los hijos en " 0dp "
  • establece el android: weightSum del padre (edit: como Jason Moore notó, este atributo es opcional, porque por defecto se establece en la suma layout_weight de los niños)
  • establezca el android:layout_weight de cada niño proporcionalmente (por ejemplo, weightSum="5", tres niños: layout_weight = "1", layout_weight = " 3", layout_weight = "1")

Ejemplo:

    <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:weightSum="5">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:text="2" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="3" />

    </LinearLayout>

Y el resultado:

Ejemplo de peso de diseño

 633
Author: Anke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-18 15:00:04

Es android:layout_weight. El peso solo puede utilizarse en LinearLayout. Si la orientación de linearlayout es Vertical, entonces use android:layout_height="0dp" y si la orientación es horizontal, entonces use android:layout_width = "0dp". Funcionará perfectamente.

 49
Author: Manoj Seelan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-16 15:51:34

Esta imagen resume el diseño lineal.

Diseño Lineal y Peso

Puede seguir este enlace para obtener más información sobre el tema. Solo Matemáticas-Vistas, Grupos de vistas y Diseños

Tutorial De Video Para Diseño Lineal: Ancho, Alto Y Pesos

Tutorial de Diseño Lineal de Android

 19
Author: Cheezy Code,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-15 10:06:29

Intente establecer el layout_width de ambos botones en "0dip" y el weight de ambos botones en 0.5

 14
Author: jqpubliq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-14 11:16:34

LinearLayout permite asignar un peso a niños individuales. Este atributo asigna un valor" importance " a una vista, y le permite expandirse para llenar cualquier espacio restante en la vista padre. El peso predeterminado es cero

Cálculo para asignar cualquier Espacio restante/Extra entre hijo. (no el espacio total)

Space assign to child = (child individual weight) / (suma del peso de cada niño en Diseño lineal)

Ejemplo (1): si hay son tres cuadros de texto y dos de ellos declaran un peso de 1, mientras que el tercero no tiene peso (0), entonces Espacio restante / Extra asignar a

1st text box = 1/(1+1+0) 
2nd text box = 1/(1+1+0) 
3rd text box = 0/(1+1+0) 

Ejemplo (2) : digamos que tenemos una etiqueta de texto y dos elementos de edición de texto en una fila horizontal. La etiqueta no tiene layout_weight especificada, por lo que ocupa el espacio mínimo requerido para renderizar. Si el layout_weight de cada uno de los dos elementos de edición de texto se establece en 1, el ancho restante en el diseño principal se dividirá igualmente entre ellos (porque afirmamos que son igualmente importantes).

calculation : 
1st label = 0/(0+1+1) 
2nd text box = 1/(0+1+1) 
3rd text box = 1/(0+1+1)

Si el primer cuadro de texto tiene un layout_weight de 1 y el segundo cuadro de texto tiene un layout_weight de 2, entonces un tercio del espacio restante se le dará al primero, y dos tercios al segundo (porque afirmamos que el segundo es más importante).

calculation : 
1st label = 0/(0+1+2) 
2nd text box = 1/(0+1+2) 
3rd text box = 2/(0+1+2) 
 6
Author: Rakesh Soni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-26 13:11:40

En el campo ancho del botón, reemplace wrap-content por 0dp.
Utilice el atributo layout_weight de una vista.

android:layout_width="0dp"  

Así es como se verá su código:

<LinearLayout
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:orientation="horizontal">

 <Button
    android:text="Register"
    android:id="@+id/register"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:padding="10dip"
    android:layout_weight="1" />

 <Button
    android:text="Not this time"
    android:id="@+id/cancel"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:padding="10dip"
    android:layout_weight="1" />    

</LinearLayout>

Layout_weight se usa para distribuir el espacio dejado en proporciones. En este caso, los dos botones están tomando " 0dp " ancho. Por lo tanto, el espacio restante se dividirá en proporción 1:1 entre ellos, es decir, el espacio se dividirá por igual entre las Vistas de los Botones.

 5
Author: Green goblin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-03 17:52:06

Como respuesta de @Manoj Seelan

Sustitúyase android:layout_weight Por android:weight.

Cuando se usa Peso con LinearLayout. debe agregar weightSum en LinearLayout y de acuerdo con la orientación de su LinearLayout debe configurar 0dp para Ancho / Alto a todas las vistas secundarias de LinearLayout

Ejemplo:

Si La orientación de Linearlayout es Vertical, entonces Establezca el ancho de todas las vistas secundarias de LinearLayout con 0dp

 <LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="vertical"
     android:weightSum="3">

     <Button
        android:text="Register"
        android:id="@+id/register"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_weight="2" />

     <Button
        android:text="Not this time"
        android:id="@+id/cancel"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_weight="1" />

  </LinearLayout>

Si la orientación Linearlayout es horizontal, luego Establece la Altura de todas las vistas secundarias de LinearLayout con 0dp.

 <LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal"
     android:weightSum="3">

     <Button
        android:text="Register"
        android:id="@+id/register"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:padding="10dip"
        android:layout_weight="2" />

     <Button
        android:text="Not this time"
        android:id="@+id/cancel"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:padding="10dip"
        android:layout_weight="1" />

  </LinearLayout>
 4
Author: ahmed hamdy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:43

Quizás establecer las propiedades layout_width de ambos botones en "fill_parent" hará el truco.

Acabo de probar este código y funciona en el emulador:

<LinearLayout android:layout_width="fill_parent"
          android:layout_height="wrap_content">

    <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="hello world"/>

    <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="goodbye world"/>

</LinearLayout>

Asegúrese de establecer layout_width en "fill_parent" en ambos botones.

 3
Author: JeremyFromEarth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-23 17:00:42
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/logonFormButtons"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:baselineAligned="true"       
        android:orientation="horizontal">

        <Button
            android:id="@+id/logonFormBTLogon"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"            
            android:text="@string/logon"
            android:layout_weight="0.5" />

        <Button
            android:id="@+id/logonFormBTCancel"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"            
            android:text="@string/cancel"
            android:layout_weight="0.5" />
    </LinearLayout>
 3
Author: Yar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-23 13:35:12

En el XML anterior, establezca el android:layout_weight del diseño lineal como 2: android:layout_weight="2"

 2
Author: Priyanka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-02 07:01:10

Además, debe agregar esto android:layout_width="0dp" para vistas secundarias [Vistas de botón] de LinerLayout

 1
Author: Rebeka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-13 19:19:15
 <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="Button 1" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:text="Button 2" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="Button 3" />

    </LinearLayout>
 1
Author: Katrina Khan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-08 08:51:32

Tienes que escribir así funciona para mí

<LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
            android:weightSum="2">

         <Button
            android:text="Register"
            android:id="@+id/register"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dip"
            android:layout_weight="1" />

         <Button
            android:text="Not this time"
            android:id="@+id/cancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dip"
            android:layout_weight="1" />
 1
Author: Dinesh Saini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-06 11:20:37

Esta es la respuesta perfecta de su problema

  <LinearLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:orientation="horizontal"  >   
     <Button 
        android:text="Register" android:id="@+id/register"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:padding="10dip" weight="1" />
     <Button 
        android:text="Not this time" android:id="@+id/cancel"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:padding="10dip" weight="1" />
  </LinearLayout>
 0
Author: Rahul Mandaliya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-06 10:55:25

Sustitúyase wrap_content por fill_parent.

 0
Author: Humberto Pinheiro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-13 19:28:37
 <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:background="#008">

            <RelativeLayout
                android:id="@+id/paneltamrin"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"

                >
                <Button
                    android:id="@+id/BtnT1"
                    android:layout_width="wrap_content"
                    android:layout_height="150dp"
                    android:drawableTop="@android:drawable/ic_menu_edit"
                    android:drawablePadding="6dp"
                    android:padding="15dp"
                    android:text="AndroidDhina"
                    android:textColor="#000"
                    android:textStyle="bold" />
            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/paneltamrin2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                >
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="150dp"
                     android:drawableTop="@android:drawable/ic_menu_edit"
                    android:drawablePadding="6dp"
                    android:padding="15dp"
                    android:text="AndroidDhina"
                    android:textColor="#000"
                    android:textStyle="bold" />

            </RelativeLayout>
        </LinearLayout>

introduzca la descripción de la imagen aquí

 0
Author: سیدرسول میرعظیمی,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-17 12:20:47

A continuación se muestran los cambios (Marcados en NEGRITA ) en su código:

<LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal">

     <Button
        android:text="Register"
        android:id="@+id/register"
        android:layout_width="0dp" //changes made here
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_weight="1" /> //changes made here

     <Button
        android:text="Not this time"
        android:id="@+id/cancel"
        android:layout_width="0dp" //changes made here
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_weight="1" /> //changes made here

  </LinearLayout>

Dado que su LinearLayout tiene orientación como horizontal, por lo tanto necesitará mantener su ancho solo como 0dp. para utilizar pesos en esa dirección . (Si su orientación fuera vertical, habría mantenido su altura solo 0dp).

Dado que hay 2 vistas y ha colocado android:layout_weight="1" para ambas vistas, significa que dividirá las dos vistas por igual en dirección horizontal (o por ancho).

 0
Author: Akshay Chopra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-17 18:00:43