Tag Archives: relative

Add a relative layout to an Android screen in Xamarin

In the tutorials so far, we have been designing Android app screens in Xamarin using a Linear Layout. A Linear Layout basically arranges buttons, text views, text fields and other elements within boundaries. These elements are usually stacked. However, Relative Layouts allow us to position elements relative to each other.

image11

Note: If you change to a Relative Layout, you will need to add elements to your screen through code instead of dragging and dropping items on from the toolbox. It is best to drag all of the elements on that you need (eg. buttons, text boxes), and then switch to a relative layout.

This tutorial assumes you already know how to create an Android app project in Xamarin. If you don’t know how to, then go back to the first tutorial.

Step 1

Open the Main.axml file (in the Resources > layouts folder) for your Android app in Xamarin. Drag a few elements on to your screen (eg. three buttons as shown below).

image4

Step 2

Click on the Source tab. Remove any gravity properties from the linear layout and remove the android:orientation=”vertical” line. Where the code says LinearLayout, replace it with RelativeLayout (both in the opening and closing tags).

image5

Go back to the Designer view and you will notice that all of the buttons are now on top of each other.

image6

Step 3

Go back to the Source tab and start typing a new line inside the Button tag for the first button. Start typing layout and you will see many options to select from. Select the android:layout_below option by double-clicking it or press Enter.

image7

Complete the line by typing android:layout_below=”@id/button1” and then close the button tag using />  …this will set the second button to be positioned below the first button. Do the same for the third button but set it so it is placed under the second button (replace @id/button1 or @id/button2 with the names of your buttons/elements).

image8

Now go back to the Designer view and you should see the three buttons placed below each other as shown below.

image9

Experiment with the different layout options from the list, for example layout_toRightof will place an element to the right side of another element.

image10

This is what the screen will look like when button2 is set to be placed to the right of button1.

image11

That’s it! You can use different combinations of layout properties to arrange the elements on your screen and position each element in relation to other elements.