What is Layout Weight in Android?

Layout Weight in Android is the priority level of space that a child view occupies in a linear layout.

How to set Layout Weight

By default, the Layout Weight is set to 0 for each child view in a linear layout. However, this can be changed manually using:

android:layout_weight="0"

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical"
android:background="@color/black">
<Button
android:id="@+id/b"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button1" />
<Button
android:id="@+id/b2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button2"
app:backgroundTint="#4CAF50" />
<Button
android:id="@+id/b3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Button3"
app:backgroundTint="#B51ACF" />
</LinearLayout>

Explanation

  • For Button “@+id/b” and “@+id/b2”, the layout_weight is set to 1. Therefore, both buttons occupy equal space in the layout.
  • For “@+id/b3”, the layout_weight is set to 2. Button3 will occupy the most space in the layout since it has a higher layout_weight as compared to Button1 and Button2.

Output of code

Free Resources