Xamarin.Forms - how to absolutely center an element on the page?

jbyrd picture jbyrd · Mar 23, 2016 · Viewed 15.6k times · Source

I have a login page using a StackLayout for the content (username, password, login button). After the user clicks the login button, I want a "loading" block set in the absolute center of the page, on top of the existing StackLayout content. For some annoying reason, this is not straightforward. It seems like a simple, common thing to do - how is this done?

Answer

Mikalai Daronin picture Mikalai Daronin · Mar 23, 2016

You used a right tag: AbsoluteLayout.


var loadingView = new StackLayout
{
    Padding = 6,
    Orientation = StackOrientation.Horizontal,
    BackgroundColor = Color.Gray,
    Children =
    {
        new ActivityIndicator
        {
            Color = Color.White,
            IsRunning = true,
            VerticalOptions = LayoutOptions.Center,
            WidthRequest = 20,
            HeightRequest = 20
        },
        new Label 
        {
            TextColor = Color.White,
            Text = "Loading...",
            VerticalOptions = LayoutOptions.Center
        }
    }
};

var layout = new AbsoluteLayout
{
    Padding = 0,
    HorizontalOptions = LayoutOptions.FillAndExpand,
    VerticalOptions = LayoutOptions.FillAndExpand,
    Children =
    {
        {
            new BoxView {Color = Color.Green}, 
            new Rectangle(0, 0, 1, 1), 
            AbsoluteLayoutFlags.All
        },
        {
            loadingView, 
            new Rectangle(0.5, 0.5, -1, -1), 
            AbsoluteLayoutFlags.PositionProportional
        }
    }
};

Or XAML:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="ArtiSO.LoadingPage">
    <ContentPage.Content>
        <AbsoluteLayout Padding="0" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
            <BoxView Color="Lime" AbsoluteLayout.LayoutBounds="0, 0, 1, 1" AbsoluteLayout.LayoutFlags="All" />
            <StackLayout Padding="6" Orientation="Horizontal" BackgroundColor="Gray" AbsoluteLayout.LayoutBounds="0.5, 0.5, -1, -1" AbsoluteLayout.LayoutFlags="PositionProportional">
                <ActivityIndicator Color="White" IsRunning="true" VerticalOptions="Center" WidthRequest="20" HeightRequest="20" />
                <Label TextColor="White" Text="Loading..." VerticalOptions="Center" />
            </StackLayout>
        </AbsoluteLayout>
    </ContentPage.Content>
</ContentPage>

Result:

Preview