Layouts in Xamarin.Forms

December 15, 2017 Xamarin, C#, Mobile

In order to build up a well-made app, it is important to keep the same look on every devices. Therefore, Xamarin.Forms provides flexible layout containers. These containers calculate positions and sizes of UI components automatically and re-calculate them when a user rotates a device or changes a view size also automatically. These layout containers that Xamarin.Forms provides are StackLayout, Grid, AbsoluteLayout and RelativeLayout and StackLayout and Grid are popular among them.

Types of layout container Types of layout container

You can use WidthRequest and HeightRequest attributes to set width and height ot each UI component instead of width and height that are normally used in general because Xamarin.Forms doesn't guarantee exact sizes as they are re-calculated based on which platform the app is run. For alignment, you can use VerticalOptions and HorizontalOptions attributes.

Width and height attributes of UI component Width and height attributes of UI component

Each platform has different way to translate sizes and resolutions so if you set WidthRequest and HeightRequest, then although absolute sizes might not be same but would have the same look.

Resolution method on major platforms.

  • Windows Phone – Effective pixels
  • iPhone – Points
  • Androind – Density-independent pixels

UI component size on each platform UI component size on each platform

Let's look into two popular layout containers, StackLayout and Grid.

StackLayout is just to stack up UI components in vertical way. As it is very simple, it is also used for building up prototypes.

StackLayout container StackLayout container

Grid is similar to table. You can set the size of rows and columns in <Grid> tag and can set where each UI component locates by Grid.Row and Grid.Column. Besides, You can make the layout flexible using attributes like RowSpan and ColumnSpan in HTML.

Grid container Grid container

In general, layout containers and UI components have same attributes like the web design such as spacing, padding and margin. Hence, if you already know how to design a webpage, it would be easier to understand the layouts in Xamarin.Forms.

Happy Coding!