Relative Layout Code Snippet for Android Studio

 

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

Android Relative Layout Example

A relative layout is the second most common type of Layout used in Android Studio after Linear Layout. In relative layout, the position of the various other UI elements in it are mentioned relative to each other, i.e the position of one element depends on the other. A relative layout is usually useful in those cases where you usually use a large number of nested linear layouts. The other type of layout available is Table Layout.

Inserting a Relative Layout in your app

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

You can specify your own layout width and height. You can set a background for the layout using the android:background property. In relative layout, the position of the UI elements are decided relative to their parent or relative to other UI elements. This gives a much  needed flexibility to the layout so that we can position our elements the way we want it to be. You can place an element upward, downward, right or left with respect to other element. 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 android:gravity to specify how an UI element should arrange it’s contents on both X-Y axis.

 

Different Layout Attributes

There are different attributes to position a UI element in Relative Layout with respect to other UI Elements. Some of the most commonly used ones are:-


  •  

 

An example of Relative layout is shown in the Image below:-

Relative layout example code for Android Studio

 

The Full Java Code along with the XML layout for the above UI 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/RelativeLayout

Comment down below if you are facing any problems.

 

Also Read:-

Leave a Reply

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