LinearLayout
es un grupo de vistas que alinea todos los elementos secundarios en una sola dirección, de forma vertical o
horizontalmente. Puedes especificar la dirección del diseño con el
android:orientation
.
Figura 1: Una LinearLayout con tres en sentido horizontal
orientados a niños.
Todos los elementos secundarios de una LinearLayout se apilan uno tras otro.
de modo que una lista vertical solo tiene un elemento secundario por fila, sin importar el ancho que tengan. R
horizontal tiene solo una fila de altura y es la altura del elemento secundario más alto,
además de relleno. Un LinearLayout respeta los márgenes entre
hijos y la gravedad, derecha, centro o izquierda
la alineación de cada elemento secundario.
Grosor del diseño
LinearLayout también admite la asignación de un peso a
hijos o hijas individuales con el
android:layout_weight
. Este atributo asigna una “importancia” valor a una vista en términos de
cuánto espacio ocupa en la pantalla. Un valor de peso más alto le permite expandir
para llenar el espacio restante en la vista superior. Las vistas secundarias pueden especificar un peso
y cualquier espacio restante en el grupo de vistas se asigna a los elementos secundarios
proporcionalmente en función del peso declarado. El valor predeterminado es cero.
Distribución equitativa
Para crear un diseño lineal en el que cada elemento secundario use la misma cantidad de espacio
en la pantalla, configura la
android:layout_height
de cada vista a "0dp" para un diseño vertical, o a la
android:layout_width
de cada vista a "0dp" para obtener un diseño horizontal. Luego, configura
android:layout_weight de cada vista a "1".
Distribución no equitativa
También puedes crear diseños lineales en los que los elementos secundarios usen diferentes
cantidades de espacio en la pantalla. Considera los siguientes ejemplos:
Supongamos que tienes tres campos de texto: dos con un valor de peso de 1 y un
tercero con el valor de ponderación predeterminado de 0. El tercer campo de texto, con el
valor de peso de 0, ocupa solo el área que requiere su contenido. El otro
dos campos de texto, con el valor de grosor de 1, se expanden de la misma forma para rellenar los
espacio restante después de que se mide el contenido de los tres campos.
En cambio, tienes tres campos de texto en los que dos tienen un valor de ponderación de 1.
y el tercero tiene un peso de 2, luego el espacio que queda después de
el contenido de los tres campos se mide de la siguiente manera: mitad para
el campo con el valor de ponderación de 2 y la mitad dividido por igual entre las
campos con el valor de ponderación de 1.
En la siguiente figura y el siguiente fragmento de código, se muestra cómo podrían funcionar los pesos de diseño en una
"enviar mensaje" actividad. El campo Para, la línea Asunto y el botón Enviar solo ocupan la altura que necesitan. El área de mensajes
ocupa el resto de la altura de la actividad.
Figura 2: Tres campos de texto y un botón en una orientación vertical
LinearLayout
Para obtener información detallada sobre los atributos disponibles para cada vista secundaria de un
LinearLayout, consulta
LinearLayout.LayoutParams
El contenido y las muestras de código que aparecen en esta página están sujetas a las licencias que se describen en la Licencia de Contenido. Java y OpenJDK son marcas registradas de Oracle o sus afiliados.
Última actualización: 2025-07-27 (UTC)
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Falta la información que necesito","missingTheInformationINeed","thumb-down"],["Muy complicado o demasiados pasos","tooComplicatedTooManySteps","thumb-down"],["Desactualizado","outOfDate","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Problema con las muestras o los códigos","samplesCodeIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-07-27 (UTC)"],[],[],null,["# Create a linear layout\n\nTry the Compose way \nJetpack Compose is the recommended UI toolkit for Android. Learn how to work with layouts in Compose. \n[Column or Row →](/jetpack/compose/layouts/basics) \n\n[LinearLayout](/reference/android/widget/LinearLayout)\nis a view group that aligns all children in a single direction, vertically or\nhorizontally. You can specify the layout direction with the\n[`android:orientation`](/reference/android/widget/LinearLayout#attr_android:orientation)\nattribute.\n| **Note:** For better performance and tooling support, [build your layout with\n| ConstraintLayout](/training/constraint-layout). Learn more about advantages of using `ConstraintLayout` by reading [Understanding\n| the performance benefits of ConstraintLayout](https://android-developers.googleblog.com/2017/08/understanding-performance-benefits-of.html).\n**Figure 1.** A `LinearLayout` with three horizontally oriented children.\n\nAll children of a `LinearLayout` are stacked one after the other,\nso a vertical list only has one child per row, no matter how wide they are. A\nhorizontal list is only one row high, and it's the height of the tallest child,\nplus padding. A `LinearLayout` respects *margins* between\nchildren, and the *gravity*---right, center, or left\nalignment---of each child.\n\nLayout weight\n-------------\n\n`LinearLayout` also supports assigning a *weight* to\nindividual children with the\n[`android:layout_weight`](/reference/android/widget/LinearLayout.LayoutParams#attr_android:layout_weight)\nattribute. This attribute assigns an \"importance\" value to a view in terms of\nhow much space it occupies on the screen. A larger weight value lets it expand\nto fill the remaining space in the parent view. Child views can specify a weight\nvalue, and any remaining space in the view group is assigned to children\nproportionately, based on their declared weight. The default weight is zero.\n\n### Equal distribution\n\nTo create a linear layout in which each child uses the same amount of space\non the screen, set the\n[`android:layout_height`](/reference/android/view/ViewGroup.LayoutParams#attr_android:layout_height)\nof each view to `\"0dp\"` for a vertical layout, or the\n[`android:layout_width`](/reference/android/view/ViewGroup.LayoutParams#attr_android:layout_width)\nof each view to `\"0dp\"` for a horizontal layout. Then set the\n`android:layout_weight` of each view to `\"1\"`.\n\n### Unequal distribution\n\nYou can also create linear layouts where the child elements use different\namounts of space on the screen. Consider the following examples:\n\n- Suppose you have three text fields: two with a weight value of 1, and a third with the default weight value of 0. The third text field, with the weight value of 0, occupies only the area required by its content. The other two text fields, with the weight value of 1, expand equally to fill the space that remains after the contents of all three fields are measured.\n- If instead you have three text fields where two have a weight value of 1 and the third has a weight of 2, then the space that remains after the contents of all three fields are measured is allocated as follows: half to the field with the weight value of 2, and half divided equally between the fields with the weight value of 1.\n\nThe following figure and code snippet show how layout weights might work in a\n\"send message\" activity. The **To** field, **Subject** line, and\n**Send** button each take up only the height they need. The message area\ntakes up the rest of the activity's height.\n**Figure 2.** Three text fields and a button in a vertically oriented `LinearLayout`. \n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"utf-8\"?\u003e\n\u003cLinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:paddingLeft=\"16dp\"\n android:paddingRight=\"16dp\"\n android:orientation=\"vertical\" \u003e\n \u003cEditText\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"@string/to\" /\u003e\n \u003cEditText\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"@string/subject\" /\u003e\n \u003cEditText\n android:layout_width=\"match_parent\"\n android:layout_height=\"0dp\"\n android:layout_weight=\"1\"\n android:gravity=\"top\"\n android:hint=\"@string/message\" /\u003e\n \u003cButton\n android:layout_width=\"100dp\"\n android:layout_height=\"wrap_content\"\n android:layout_gravity=\"end\"\n android:text=\"@string/send\" /\u003e\n\u003c/LinearLayout\u003e\n```\n\nFor details about the attributes available to each child view of a\n`LinearLayout`, see\n[LinearLayout.LayoutParams](/reference/android/widget/LinearLayout.LayoutParams)."]]