Tuesday , November 12 2019
Home > Android-Studio > Linear Layout Code Snippet for Android Studio

Linear Layout Code Snippet for Android Studio

 

Welcome. In this tutorial you will learn about linear layout in Android Studio.

Android Linear Layout Example

A linear layout is the most simplest or basic kind of layout used in Android Studio.In this layout, all the UI components inside it are either arranged horizontally or vertically one after another. You can specify in which orientation you want the layout to be.. The other most commonly used type of layout is Relative layout.

Inserting a Linear Layout in your app

For inserting a linear layout in your app the <LinearLayout> tag is used, as shown in the example below:-

Here you can specify your own layout width and height. You can change the orientation to either horizontal or vertical using the android:orientation property. You can also set a background using the android:background property. Other properties like android:padding, or margin or gravity also work here in the same way as they work for other layouts. You can change the gravity to center if you want all your UI elements inside the layout to be center aligned.

Layout Weight

You can also specify weights to your individual UI elements inside Linear Layout by using the android:layout_weight attribute. This weight is like specifying importance or space allocated for individual UI elements. The child whose weight will be more will use more space inside the layout. That means if there is any empty space, then the UI elements will try to arrange themselves according to the ratio of their given weights. By default, the weight is set to zero for all the elements.

 

An example of Linear Layout is shown in the image below:-

Linear Layout Example Code for Android Studio

 

The Full Java Code along with the XML layout for creating the above layout is shown below:-

JAVA (MainActivity.java)

 

XML (activity_main.xml)

 

 

You can directly copy paste these snippets to your android studio, and they should work perfectly. Just save and run your project. You can also try to play with various other layout settings on your own and see the corresponding changes accordingly. There are a variety of properties available which can be changed to make your UI more interesting.

For a more detailed guide, you can also visit android’s official guide below:-

https://developer.android.com/reference/android/widget/LinearLayout

Comment down below if you are facing any problems.

 

Also Read:-

Check Also

Relative Layout in Android studio

Relative Layout Code Snippet for Android Studio

  Welcome. In this tutorial you will learn about Relative layout in Android Studio. Android …

Leave a Reply

Your email address will not be published. Required fields are marked *