Arranging views with Xamarin.Forms layout (2023)

Xamarin apps run on a variety of device sizes - from small phones to larger tablets - and devices can switch from portrait to landscape mode on the fly. The app's UI needs to adapt to these size and orientation changes, look good, and be functional. Every UI framework has the idea of ​​positioning and sizing elements on the screen. As systems have evolved, these layout tools have also evolved, adding features that simplify everyday layout problems. These layouts provide the ability to create adaptive user interfaces. In this article, I look at themXamarin.FormsLayout views and show how to use them to create different UI design structures.

views and layouts

The visual elements in Xamarin.Forms fall into two separate categories: controls and arrangers. Both are considered visuals, sharing a common base class (view) and are collectively referred to as views. But their missions are different.viewClasses (the controls) are responsible for collecting user input or displaying information to the user. They are called controls or widgets in other UI frameworks.

floor plans(the arrangers) serve a different purpose. A layout class is oneviewClass containing a collection of child views. It is responsible for arranging the child views in the UI. It also works with each child to determine the final render size. To be clear, layouts are also views, but are rarely called that by the community.

illustration 1shows a list of classes derived fromviewClass. Most of them fall into the input/output control category. The classes are outlined with a red rectangleillustration 1are the base classes for the layout views.

Arranging views with Xamarin.Forms layout (1)
Illustration 1:The View classes in Xamarin.Forms

layout classes

The layout classes do the work of arranging the elements on the screen. Each layout specializes in an arrangement style. If you are familiar with other XAML frameworks, many of these layout classes (shown inFigure 2) will look familiar to you, albeit with different names.

Arranging views with Xamarin.Forms layout (2)
Figure 2:Die Layoutklassen in Xamarin.Forms

The simplest layout containers are theContentView,Frame, AndScrollView. They are designed to provide some simple services to the children. Although they can contain multiple children, there is no good reason to have more than one child on these layouts. They simply don't provide layout options to help arrange multiple children. The other layouts (AbsolutesLayout,network,RelativesLayout, AndStackLayout) are characterized by arranging multiple child elements. It is common to mix and match multiple layouts in the page UI. Therefore, it's important to understand the strengths of each layout in order to create your pages.

A word about color

The Xamarin.Forms out-of-the-box color palette is small. Nineteen color constants are available. For this article I would like to use a custom color set; Here's how to do that. First create a static class and add some static properties:

namespace Common { static class Hues { public static readonly Color Sky = Color.FromHex("#226765"); öffentlich statisch readonly Color Fire = Color.FromHex("#AA4B40"); }}

In this example I used theFarbe.FromHex-Method to define the two custom colors. TheColorstruct has other methods to describe colors (ByRGB,VonHlsa, AndVonUint); Use whichever method you prefer to define your color set.

To use these custom colors on a page, add a custom XML namespace to the root element:

<ContentPage xmlns="..." xmlns:x="..." xmlns:c="clr-namespace:Common;assembly=Demo" >

I used the prefixCfor my XML namespace. Normally I would use a more readable name, e.gtogether, but I chose the shorter name to fit the example within the code snippet size limit for the magazine. Notice the use ofclr namespace:Syntax in namespace declaration: How to specify which.NETWORKuse namespace.

This snippet uses theTogethernamespace in theDemoAssembly. Look at the code snippet shown earlier and you can see that the color properties are in theCommon.HuesClass. Now that theCnamespace is registered, I can access the colors with this snippet:

BackgroundColor="{x:Static c:Hues.Sky}"

The ContentView and Frame

ContentViewis not intended to be used directly in your XAML structure. Rather, it is designed as a base class for creating your own composite views. TheFrame, which arisesContentView, is a better choice for a wrapper around a child view. Its greatest advantage is that it can present a visible border around the child. This next snippet shows how to do theoutline colorand add a drop shadow to the frame:

<Frame OutlineColor="White" HasShadow="True"> <Label Text="The Label" /></Frame>

The frame inherits a useful property,upholstery, from the Layout base class. Non-layout views do not have border or padding properties. The only way to make room around a view is to place it on a layout and set itupholsteryproperty like this:

(Video) XamarinForms : Page,Layout & Views

<Frame Padding="30"> <Label Text="The Label" /></Frame>

Because thatupholsteryproperty is part of the layout base class, it can be set for all other layout classes.

Vertical Options and Horizontal Options

Each view has a size determined by a collaboration between the child view and its layout container. Use theVertical Options,Horizontal options,width request, Andheight requestProperties to affect the final rendered size. Let's look at the default size of an element.

<Frame Padding="10,20" BackgroundColor="{x:Static c:Hues.Sky}"> <BoxView Color="{x:Static c:Hues.Fire}"/></Frame>

The example in the code snippet uses aFramelike the layout and aBoxViewas a child. TheBoxViewis a simple view useful for drawing solid color rectangles. I don't specify a width or height for theBoxView. I don't set a value for them eitherVertical OptionsAndHorizontal options.Figure 3shows the UI running on an Android emulator.

Arranging views with Xamarin.Forms layout (3)
Figure 3:Default size for BoxView on Android

By default, theBoxViewis sized to fit its container, theFrame. The blue buffer that appears around the edge of theBoxViewis located on thePadding = "10.20"property on theFrame. In this case, that means 10 pixel padding left and right and 20 pixel padding top and bottom.

The dynamics of dimensioning

Sizing and positioning can get complicated, especially with demanding multi-layer interfaces. Here are some pointers to help understand how the system works.

Each view has a desired size, the size at which it should be rendered if possible. The desired size is calculated internally within the child view. Take a label as an example. Its desired width depends on many factors. How many characters are in theTextProperty? What is the font size?

The same applies to the desired height. The desired height is higher when there are many characters, a large font size and word wrapping are enabled. In general, it's better to let the view decide its own size. You can override the desired size if needed by adjusting thewidth requestAndheight requestproperty in the child view.

There will be times when the requested size (or desired size) is smaller than the layout container. For example, a 180 pixel wide label within a 300 pixel widthStackLayout. In this scenario, the panel moves to theVertical OptionsAndHorizontal options-Properties to determine where to place the child within the extra white space. Several settings are available for thelayout optionsCount. The discussion here revolves around theHorizontal optionsand it's similar for thatVertical OptionsProperty.

  • Start
  • Center
  • End
  • Fill (default)
  • StartAndExpand
  • CenterAndExpand
  • EndAndExpand
  • FillAndExpand

I'll look at the top four items on this list.LayoutOptions.Startsets the child width to the requested size, and then positions the element to the side of the container. In left-to-right languages ​​the start position is the left side of the container, in right-to-left languages ​​the start position is on the right side.LayoutOptions.Enddoes the opposite and positions the element on the right side in left-to-right languages ​​and on the left side in right-to-left languages.LayoutOptions.Centercenters the element and keeps it the desired size.LayoutOptions.Fillstretches the width of the child to match the parent container.LayoutOptions.Fillis the defaultLayoutOptionAttitude.

Check out this next snippet. TheBoxViewdoesn't specify a size, so it gets the default size. Nor does it indicate thatVertical OptionsorHorizontal optionseither, so it defaults to theLayoutOptions.FillValue. As a result of these settings, the parentFramestretches theBoxViewfit horizontally and vertically.

<Frame Padding="30" BackgroundColor="#226765"> <BoxView BackgroundColor="#AA4B40" /></Frame>

overwritelayout options, use this XAML:

<Frame Padding="30" BackgroundColor="#226765"> <BoxView BackgroundColor="#AA4B40" HorizontalOptions="End" VerticalOptions="Start" /></Frame>

Now theBoxViewis in the top left on my phone (because English is a left-to-right language). TheBoxViewis not stretched within the frame, so it reverts to its default size of 40x40 pixels.

ScrollView

ScrollViewis useful when the child content is larger than will fit in the UI. For example, if the text content on a page is too large to fit the screen, wrap the label in aScrollView. This can make your UI readable on smaller screen sizes. Content that fits on a big-screen phone like the Nexus 6 is also readable on the smaller Moto G phone. This code snippet shows a tallBoxViewwithin theScrollView:

(Video) Visual UI Elements(Page,Layout and Views)-Xamarin in Hindi

<ScrollView Padding="30" BackgroundColor="{x:Static c:Hues.Sky}" > <BoxView Color="{x:Static c:Hues.Fire}" HeightRequest="1400" /></ScrollView>

Figure 4shows the result. If you look closely at the Android and Windows Phone screenshots, you can see the scroll bar on the right side of the screen. It's not visible on the iPhone screenshot, but that's due to the limitations of my screen capture software.

Arranging views with Xamarin.Forms layout (4)
Figure 4:ScrollView in action

StackLayout

This layout is one of my favorites and I use it throughout my UI. It has a simple task: position the children in a stack, either horizontally or vertically. The order in which the children are added to the layout is the order in which they are stacked. This snippet adds twoBoxViewswith defaultHorizontal options, and three more with specificHorizontal optionsSentence:

<StackLayout > <!-- standardmäßig HorizontalOptions="Fill"--> <BoxView Color="{x:Static c:Hues.Fire}" /> <BoxView Color="{x:Static c:Hues.Sky} " /> <BoxView Color="{x:Static c:Hues.Sky}" HorizontalOptions="Start"/> <BoxView Color="{x:Static c:Hues.Fire}" HorizontalOptions="Center"/> < BoxView Color="{x:Static c:Hues.Sky}" HorizontalOptions="End"/></StackLayout>

Figure 5shows the results.

Arranging views with Xamarin.Forms layout (5)
Figure 5:StackLayout on the devices

Each element is positioned directly below the previous one, with a gap of six pixels between elements. The distance is adjustable withDistanceProperty.

<StackLayout Spacing="18">

Figure 6is an example of aStackLayoutwith horizontal alignment:

<StackLayout Orientation="Horizontal"> <Image Source="twitter.png"/> <Image Source="facebook.png"/> <Image Source="pinterest.png"/></StackLayout>
Arranging views with Xamarin.Forms layout (6)
Figure 6:Horizontal layout of images

Two-dimensional layout with the grid

The grid is a proven way to arrange information in a two-dimensional space. Designers determine the placement of important elements with grid lines. With the formalization of UI design, the grid has emerged as the most important tool in the layout workflow.

The Xamarin grid is similar to other XAML-based grids, although it has one feature you haven't seen before. It wears thecolumn spacingAndline spacingAttributes that define how much space should be placed between the rows and columns in the grid.

<Grid ColumnSpacing="6" RowSpacing="4">

Aside from this small change, the other grid attributes are familiar territory for XAML developers. For those new to XAML, here's the overview. You define columns within a column definition section and rows in a row definition section:

<Grid ColumnSpacing="6" RowSpacing="4" BackgroundColor="{x:Static c:Hues.Sky}"> <Grid.ColumnDefinitions> <ColumnDefinition Width="100"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="3*"/> <RowDefinition Height="3*"/> </Grid.RowDefinitions> <!-- Untergeordnete Elemente kommen hierher. --></Raster>

This snippet creates a grid with two rows and two columns. To control the size of the row or column, use the size option specified withGridUnitTypeCount. There are three options forGridUnitTypeSizes:Absolut,Auto, AndStern.

The width of an absolute-size column is hard-coded to the specified value. This example shows two columns with fixed widths:

<Grid.ColumnDefinitions> <!-- Absolute size--> <ColumnDefinition Width="113"/> <ColumnDefinition Width="37"/></Grid.ColumnDefinitions>

The width of an auto-sizing column is determined by its content. An auto-fit column with a 120-pixel caption and 80-pixel button is set to 120 pixels. This example shows two columns with automatically adjusted widths:

<Grid.ColumnDefinitions> <!-- Auto size--> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>

The width of a star-sized column (also known as proportional size) is determined by its relationship to the other columns in the grid. Look at this example:

<Grid WidthRequest="450"> <Grid.ColumnDefinitions> <ColumnDefinition Width="113"/> <ColumnDefinition Width="37"/> <ColumnDefinition Width="2*"/> <ColumnDefinition Width="3*"/ > <ColumnDefinition Width="5*"/> </Grid.ColumnDefinitions></Grid>

To determine the sizes of each column, the grid starts by resolving the Absolute-Size and Auto-Size columns. In this case, the two absolute columns total 150 pixels. The grid requested a width of 450 pixels. Assuming the raster is rendered at 450 pixels, that leaves 300 pixels for the remaining three columns. Next, the grid counts a sum of all star-sized items (2* + 3* + 5*=10*) and divides each column by the column star value. The results for the third, fourth, and fifth columns are (2/10 (20%), 3/10 (30%), and 5/10 (50%)). Using these percentages, the final rendered sizes for the columns are: 113, 37, 60, 90, and 150.

(Video) XAM135 - Layout in Xamarin.Forms

Even if I don't show examples of itrow definitions, they work the same way to adjust row height.

Once the grid is defined, it's time to add the children. Unless otherwise noted, a child is placed in column 0, row 0. To change the default placement, use theGrid.ColumnAndGrid.RowAttribute.

<BoxView Grid.Row="1" Grid.Column="2"/>

You can also use theGrid.ColumnSpanAndGrid.RowSpan-Attributes to specify how many columns and rows the child view should span.

<BoxView Grid.RowSpan="2" Grid.ColumnSpan="4" />

AbsolutesLayout

Use theAbsolutesLayoutwhen you need precise control over the x and y positions and the width and height of the child elements. It has its place in the layout world. In most situations it is better to use one of the other layouts; They ensure a more appealing design. The absolute layout is reminiscent of the old days when we brutally positioned screen elements. While that's less common now, it has its place for certain layout challenges.

Each child element describes its position and size with theAbsoluteLayout.LayoutBoundsAttribute. Use a comma-separated list to specify the bounding box values ​​(x, y, width, and height):

<AbsoluteLayout> <BoxView AbsoluteLayout.LayoutBounds="90, 50, 75, 25" BackgroundColor="{x:Static c:Hues.Sky}" /></AbsoluteLayout>

The parameters for theAbsoluteLayout.LayoutBoundsAttribute are as follows:

  • X: Horizontal Die Position of Elements
  • Y: The vertical position of the element
  • Broad: The width of the element
  • Height: The height of the element

This snippet results in an image that is 75 pixels wide and 25 pixels tallBoxViewpositioned 90 pixels to the left and 50 pixels down from the upper-left corner of its parent.

As I said, hard-coded size and position are a throwback to earlier times. It is better to use a proportional size in theAbsolutesLayout. To switch to proportional layout, use theLayoutFlagAttribute:

<AbsoluteLayout> <BoxView AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="90, 50, 75, 25" BackgroundColor="{x:Static c:Hues.Sky}" /></AbsoluteLayout>

This sets all four values ​​in theLayoutGrenzenAttribute to proportional size. Now theBoxViewis 75% of the width of the parent element instead of 75 pixels. The same applies to the other three values; for example the top of theBoxViewis halfway in the parent element and not 50px from the top.

TheatFlag sets each value in the bounding box to be proportional. There are other flags that turn on proportional values ​​for the other bounding box values:

<AbsoluteLayout> <BoxView AbsoluteLayout.LayoutFlags="WidthProportional" AbsoluteLayout.LayoutBounds="90, 50, 75, 25" BackgroundColor="{x:Static c:Hues.Sky}" /></AbsoluteLayout>

Theproportional to widthFlag sets the width to a proportional value and the other three values ​​remain absolute. Check out the Xamarin documentation to see all combinations.

Proportional sizes are an improvement over absolute sizes; An even better option is to useRelativesLayout.

RelativesLayout

ARelativesLayoutis useful for creating adaptive layouts where the UI adapts to screen rotation and screen size. Use it to arrange UI elements based on the position and dimensions of their parents and the positions and dimensions of other views. Another key benefit ofRelativesLayout(and theAbsolutesLayout) is the ability to overlap or layer child elements.

(Video) Xamarin Forms #49: Layout CollectionView | Add SearchBar & EmptyView

Every element in theRelativesLayoutcan define a constraint, which is a rule that defines how the element relates to other elements (parent, sibling).

Several constraint types are available:

  • RelativeLayout.YConstraint
  • RelativeLayout.XConstraint
  • RelativeLayout.WidthConstraint
  • RelativeLayout.HeightConstraint

The names are self-explanatory. It's not difficult to understand what each constraint type does. Next, I'll look at some of the constraints to show you how they work.

Consider a scenario where you have two views, a label and a button. The label is at the top of theRelativesLayoutand set to 90% of the width of the parent. The button is below the label and corresponds to the width of the label and is positioned on the left edge of the button. The width of theRelativesLayoutchanges when the user rotates the phone to landscape mode. The width of the label has to be adjusted accordingly and the left position of the button has to change as well.

A constraint can have the following values:

  • Elementname: The name of the element to which the constraint is relative
  • Typ: Whether the constraint is relative to the parent or another view
  • Property: Which property of the relative member to use for the constraint
  • Factor: The multiplier for the constraint
  • Constantly: An offset for the constraint

Here is the XAML for the label:

<RelativeLayout BackgroundColor="{x:Static c:Hues.Sky}" > <Label x:Name="MainLabel" Text="Example" BackgroundColor="Black" FontSize="24" RelativeLayout.WidthConstraint="{ConstraintExpression Type= RelativeToParent, Eigenschaft=Breite, Faktor=0,9, Konstante=0}" RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToParent, Eigenschaft=X, Konstante=20}" />

The label has two limitations,width constraintAndXConstraint. TheType=RelativeToParentparameter sets the constraint to the parentRelativesLayout. The width of the label is linked to the parent widthproperty=widthvalue and theFactor=0.9sets the label width to 90% of the parent. TheProperty=XAndConstantly = 20values ​​set theXPosition des Labels.

Here is the XAML for the button:

<Button Text="Do Work" RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToView, ElementName=MainLabel, Property=Y, Constant=40}" RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToView, ElementName=MainLabel, Property=X , Konstante=0}" />

Notice the use ofType=RelativeToViewAndElementName=Main Labelto set theYConstraintAndXConstraintfor themain stickerView. Next, set theProperty=YAndConstantly = 40Values ​​to position the button 40 pixels below the label. Use those tooProperty=XAndPermanently=0values ​​to keep the left edge of the button aligned with the left edge of the label.

Figure 7show theRelativesLayoutin action on the Android emulator.

Arranging views with Xamarin.Forms layout (7)
Figure 7:Label and Button and RelativeLayout

Figure 8shows the same user interface in landscape mode.

Arranging views with Xamarin.Forms layout (8)
Figure 8:Label and Button and RelativeLayout in landscape format

Diploma

In general, Xamarin layout views follow a structure similar to other XAML frameworks. They're designed to work in a cross-platform situation, which leads to uncharted territory for XAML veterans. Each layout solves a specific problem. Once you understand how each one works, you'll find that you can overlay them to create the UI of your dreams.

Videos

1. Grid Layout in Xamarin Forms- Xamarin Forms in Hindi
(SPTutorials)
2. [XAM120] Layout in Xamarin Forms
(Xamarin University)
3. Learn Live - Customize layout in .NET MAUI XAML pages
(Microsoft Developer)
4. [XAM120] Layout in Xamarin.Forms
(Xamarin University)
5. [XAM135] The Layout Process in Xamarin.Forms
(Xamarin University)
6. [XAM130] Reusing XAML Views in Xamarin.Forms
(Xamarin University)
Top Articles
Latest Posts
Article information

Author: Dan Stracke

Last Updated: 03/06/2023

Views: 6050

Rating: 4.2 / 5 (63 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Dan Stracke

Birthday: 1992-08-25

Address: 2253 Brown Springs, East Alla, OH 38634-0309

Phone: +398735162064

Job: Investor Government Associate

Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.