Xamarin.Forms - 如何绝对居中页面上的元素?

时间:2016-03-23 15:44:07

标签: loading center xamarin.forms absolutelayout

我有一个使用StackLayout登录页面的内容(用户名,密码,登录按钮)。用户点击登录按钮后,我想要一个" loading"块设置在页面的绝对中心,位于现有StackLayout内容之上。出于某些恼人的原因,这并不简单。这似乎是一件简单而常见的事情 - 这是怎么做到的?

2 个答案:

答案 0 :(得分:16)

您使用了正确的标记: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
        }
    }
};

或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>

结果:

Preview

答案 1 :(得分:0)

要使ActivityIndi​​cator居中,您可以尝试以下网格提示:

<ContentPage.Content>
    <Grid>
        <StackLayout>
            <Label Text="All content view in this StackLayout :D" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" />
        </StackLayout>
        <ActivityIndicator
            Color="#006699"
            HorizontalOptions="CenterAndExpand"
            VerticalOptions="CenterAndExpand"
            IsVisible="True"
            IsRunning="True" />
    </Grid>
</ContentPage.Content>

enter image description here