Key Takeaways
- A
LinearLayoutarranges child views in one vertical column or horizontal row; it doesn't automatically wrap them onto another line. - XML declares the view hierarchy separately from Activity code. Load the layout with
setContentView(R.layout.main_view). match_parentandwrap_contentcontrol individual dimensions, not CSS-style appearance.- Use string resources, a persistent input label, and direction-aware
start/endalignment.
This Android LinearLayout example builds a vertical name field and Submit button in XML, then displays them from a Kotlin or Java Activity. LinearLayout is a container—a ViewGroup—that places its children sequentially along one axis. XML lets you declare that structure separately from the code that controls the screen.
If you know HTML/CSS, the nested elements will look familiar. The analogy stops at layout behavior: Android uses parent-driven measurement, not CSS layout rules. Our comparison of CSS layout models provides a web-side reference point.
Getting Started
- In Android Studio, use a Views-based project or add an Empty Views Activity. Choose Kotlin for the main example, or Java for the alternative below. Keep the generated Activity registration, AppCompat-compatible theme, and dependencies.
- In a typical module named
app, createapp/src/main/res/layout/main_view.xml. This is a module-relative resource directory, not a filesystem-root/res/layoutdirectory. - You can also right-click the module's
layoutdirectory and select New > Layout Resource File. Entermain_viewas the filename andLinearLayoutas the root element. - Open the generated
MainActivity.ktorMainActivity.javain your app's package. Android Studio's Android view groups both Kotlin and Java sources underjava.
The filename becomes the resource identifier: main_view.xml is referenced as R.layout.main_view. Use lowercase names with underscores; layout resource basenames cannot contain capitals or hyphens.
Build the Android LinearLayout XML Example
Add the String Resources
Add these entries inside the existing <resources> element in app/src/main/res/values/strings.xml; don't remove the template's existing strings. The block below shows a complete resource file for reference. Layouts reference these values with @string/..., keeping user-visible text available for localization.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="name_label">Name</string>
<string name="name_hint">Enter your name</string>
<string name="submit">Submit</string>
</resources>Create main_view.xml
Paste this complete layout into main_view.xml. The label, input, and button appear in XML order because the container uses vertical orientation.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingStart="16dp"
android:paddingTop="16dp"
android:paddingEnd="16dp"
android:paddingBottom="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:labelFor="@+id/name_input"
android:text="@string/name_label" />
<EditText
android:id="@id/name_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/name_hint"
android:inputType="textPersonName" />
<Button
android:id="@+id/submit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:layout_gravity="end"
android:text="@string/submit" />
</LinearLayout>The visible TextView label remains present after someone types. Its android:labelFor associates it with the input for accessibility services; the hint supplies additional guidance rather than serving as the only label. android:inputType="textPersonName" identifies the expected text as a person's name—it isn't name validation.
Here is the intended arrangement in a left-to-right layout. System-bar spacing, handled by the Activity below, is omitted:
+-----------------------------------+
| 16dp top padding |
| Name |
| [ Enter your name ] |
| 12dp top margin |
| [ Submit ] |
| |
+-----------------------------------+
^ ^
16dp start padding 16dp end paddingUnderstand Sizing, Orientation, and Alignment
match_parent vs wrap_content
These values apply independently to android:layout_width and android:layout_height. They are measurement requests interpreted by the parent, not general styling instructions.
| Value | Meaning for that dimension | Use in this example |
|---|---|---|
match_parent | Request the parent's available size, accounting for parent padding and applicable child margins. | The root fills its content area; the input fills the available width. |
wrap_content | Request enough size for content and padding, subject to minimum sizes and the parent's constraints. | The children request content-based heights; the label and button request content-based widths. |
The input's full width comes from layout_width="match_parent", not from its wrap_content height. Likewise, the button is not full-width because its width is wrap_content. Padding creates space inside the parent; layout_marginTop creates space outside the button.
Vertical and Horizontal Orientation
android:orientation="vertical" stacks children in a column. Changing it to horizontal places them in a row, but doesn't automatically redistribute their widths or wrap overflowing children. Set orientation explicitly rather than relying on the horizontal default.
Don't simply switch this form to horizontal and expect a balanced row: the input still requests the parent's available width. Redesign the child dimensions when changing the stacking axis.
Align the Button with layout_gravity
In this vertical layout, the stacking axis is vertical and the cross-axis is horizontal. android:layout_gravity="end" positions the button at the horizontal end of its available space; it doesn't move the button to the bottom of the screen or change the stacking order. With a full-width button, that alignment would have no visible room to work.
Don't confuse layout_gravity, which positions a child within its parent, with gravity, which controls alignment of content inside a view or children inside a container. Use start/end rather than physical left/right values so alignment follows layout direction. Ensure the manifest's <application> has android:supportsRtl="true" when supporting right-to-left locales.
Linking Your View to an Activity
setContentView(R.layout.main_view) inflates the XML—creates its view objects—and installs that hierarchy as the Activity's content. Call it from onCreate() after super.onCreate(...).
The examples also handle window insets: space occupied by system bars and display cutouts. Edge-to-edge windows can otherwise place controls behind system UI. The WindowCompat.enableEdgeToEdge call requires AndroidX Core 1.17.0 or newer; keep your project's current stable dependencies rather than downgrading to that minimum. See the WindowCompat API reference.
Choose one implementation below. Replace the example package with your generated package, keep the Activity registered in the manifest, and replace—not duplicate—the template's existing content and root-inset setup.
Kotlin Activity
package com.example.linearlayout
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.enableEdgeToEdge(window)
setContentView(R.layout.main_view)
val root = findViewById<View>(R.id.main)
val left = root.paddingLeft
val top = root.paddingTop
val right = root.paddingRight
val bottom = root.paddingBottom
ViewCompat.setOnApplyWindowInsetsListener(root) { view, insets ->
val safe = insets.getInsets(
WindowInsetsCompat.Type.systemBars() or
WindowInsetsCompat.Type.displayCutout()
)
view.setPadding(
left + safe.left,
top + safe.top,
right + safe.right,
bottom + safe.bottom
)
insets
}
}
}Java Activity
package com.example.linearlayout;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WindowCompat.enableEdgeToEdge(getWindow());
setContentView(R.layout.main_view);
View root = findViewById(R.id.main);
final int left = root.getPaddingLeft();
final int top = root.getPaddingTop();
final int right = root.getPaddingRight();
final int bottom = root.getPaddingBottom();
ViewCompat.setOnApplyWindowInsetsListener(root, (view, insets) -> {
Insets safe = insets.getInsets(
WindowInsetsCompat.Type.systemBars()
| WindowInsetsCompat.Type.displayCutout()
);
view.setPadding(
left + safe.left,
top + safe.top,
right + safe.right,
bottom + safe.bottom
);
return insets;
});
}
}Both implementations preserve the XML padding and add safe-area spacing to it. Capturing the original padding once prevents repeated inset dispatches from accumulating extra padding. The listener follows Android's Views edge-to-edge guidance.
Run the app on an emulator or device. You should see the Name label, a full-width input, and an end-aligned Submit button underneath it. This example renders the form only: the button has no submission handler.
Keeping layout declarations separate from Activity behavior is one small design boundary. For the broader architecture discussion, read our comparison of MVC and MVVM.
Choose LinearLayout, ConstraintLayout, or Compose
- LinearLayout: Use it for a simple row or column in a Views-based screen. This form doesn't need a more elaborate container.
- ConstraintLayout: Consider it when a Views-based screen needs relationships between multiple elements or when nested containers make positioning difficult. It supports complex layouts with a flatter hierarchy. RelativeLayout remains available, but isn't the first option to reach for here.
- Jetpack Compose: Follow Google's current recommendation for new UI. You can introduce Compose incrementally into an existing Views app rather than rewriting everything at once.
You can also construct Views programmatically in Kotlin or Java. XML is useful for declarative View hierarchies, not universally preferable to every other approach.
Common Mistakes
- Expecting end alignment to shrink a full-width button. Change its width to
wrap_contentif you want visible space beside it. - Using a disappearing hint as the only field label. Keep the visible label and its
labelForrelationship. - Assuming input configuration validates data.
textPersonNamedescribes input; decide your application's validation rules separately. - Checking only the preview. Run the form with the keyboard open, larger font settings, and an RTL locale before shipping. The sample's inset listener handles system bars and cutouts, not keyboard avoidance. See the edge-to-edge guide for keyboard-inset handling.
FAQ
How do I create a vertical LinearLayout in Android XML?
Use a LinearLayout root with android:orientation="vertical", then declare its children in the order you want them stacked. Give the container and every child layout_width and layout_height values.
What is the difference between match_parent and wrap_content?
match_parent requests the parent's available size for one dimension; wrap_content requests enough space for content and padding, subject to minimum sizes and parent constraints. Width and height are evaluated independently.
How do I align a child view to the end of a LinearLayout?
In a vertical LinearLayout, use android:layout_gravity="end" on the child and leave horizontal space available, typically with layout_width="wrap_content". End alignment follows layout direction and does not move the child to the bottom.
How do I load an XML layout in a Kotlin Activity?
Override onCreate(), call super.onCreate(savedInstanceState), and then call setContentView(R.layout.main_view). The identifier comes from the resource filename main_view.xml.
Should I use LinearLayout, ConstraintLayout, or Jetpack Compose?
Use LinearLayout for simple one-axis arrangements and ConstraintLayout for more complex positioning in an existing Views-based UI. Google recommends Compose for new UI; supported View components are now in maintenance mode.
Further Reading
- Create a linear layout — orientation, stacking, and space distribution.
- Layouts in Views — XML inflation, sizing, padding, and margins.
- String resources — reusable, localizable user-facing text.
- Accessibility principles for Views — labels and editable controls.
- Support different languages and cultures — RTL support and direction-aware attributes.
- Display content edge-to-edge in Views — system-bar, cutout, and keyboard considerations.
- Build a responsive UI with ConstraintLayout — complex View positioning without deep nesting.
- Android UI development is Compose First — Google's 2026 direction and View-system support policy.
