Android LinearLayout
LinearLayout is used to align a group of widgets either horizontally or vertically.
In this tutorial, we will learn about LinearLayout, how to use it to display a group of widgets in a LinearLayout, and use its attributes to transform its dimensions, position, alignment, orientation, etc.
LinearLayout in XML Activity File
To define a LinearLayout in layout XML file, the sample code snippet is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- children -->
</LinearLayout>
layout_width and layout_height attributes are mandatory.
Height and Width of LinearLayout
To define width and height of LinearyLayout, use android:layout_width and android:layout_height attributes.
We can provide a specific value in dp, sp, etc., like 200dp, 200sp, etc., or to match the parent, or wrap content, etc.
To set width or height of LinearLayout to match its parent’s width or height, assign android:layout_width or android:layout_height attribute with "match_parent"
respectively.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- children -->
</LinearLayout>
To set width or height of LinearLayout to wrap its children, assign android:layout_width or android:layout_height attribute with "wrap_content"
respectively.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<!-- children -->
</LinearLayout>
We can also specify the width or height in display units like dp, in, mm, pt, px or sp,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="wrap_content">
<!-- children -->
</LinearLayout>
Orientation of LinearLayout
The default orientation of LinearyLayout is horizontal. But we can specify a orientation.
To define orientation of LinearyLayout, whether vertical or horizontal, use android:orientation attributes.
Horizontal LinearyLayout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<!-- children -->
</LinearLayout>
Vertical LinearyLayout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- children -->
</LinearLayout>
How To s of LinearLayout
The following list covers some of the how tos for a LinearLayout.
- How to arrange children of LinearLayout horizontally in Android?
- How to arrange children of LinearLayout vertically in Android?
- How to center align of LinearLayout in Android?
Conclusion
In this Kotlin Android Tutorial, we learned about LinearLayout in Android and how to use LinearLayout in Android applications.