堆栈布局内的绝对布局

时间:2016-10-08 13:08:02

标签: xamarin.forms

我试图在StackLayout内部的页面右下角添加一个浮动按钮

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:fab="clr-namespace:FAB.Forms;assembly=FAB.Forms"
    x:Class="Hura.Pages.LatestNews"
    Title="Latest news">
    <StackLayout Spacing="10" Padding="5">
        <Label Text="Latest news" FontSize="Medium"/>
        <ListView x:Name="lsvNews"/>

        <Label Text="Latest activities" FontSize="Medium"/>
        <ListView x:Name="lsvActivities"/>

        <Label Text="Good Mording" FontSize="Large" HorizontalOptions="Center"/>
        <AbsoluteLayout x:Name="xyz"
            BackgroundColor="Transparent"
            HorizontalOptions="End"
            VerticalOptions="End">
            <Button Text="gggggg"/>
        </AbsoluteLayout>
    </StackLayout>
</ContentPage>

但按钮出现在标签旁边。但我希望它出现在标签上方,而不是低于它。

enter image description here

如何将按钮放在标签上方的左下角?

2 个答案:

答案 0 :(得分:3)

这里的问题是StackLayout只是按照添加顺序排列项目。因此,在您添加AbsoluteLayout后添加了Label,您的Button将显示低于Label

显然,您可以将Label移到AbsoluteLayout下面并获得您要求的效果:

...


<AbsoluteLayout x:Name="xyz"
                BackgroundColor="Transparent"
                HorizontalOptions="End"
                VerticalOptions="End">
  <Button Text="gggggg"/>
</AbsoluteLayout>
<Label Text="Good Mording" FontSize="Large" HorizontalOptions="Center"/>

...

但浮动按钮的重点是它实际上浮动高于其他内容。在您显示的示例中,您的Button永远不会浮动。为了让Button浮动其他项目,您需要将整个StackLayout添加到AbsoluteLayout。这样的事情(注意我没有测试过这段代码所以你可能需要稍微玩一下):

<AbsoluteLayout VerticalOptions="FillAndExpand"  
                HorizontalOptions="FillAndExpand">
  <StackLayout Spacing="10"
               Padding="5"
               AbsoluteLayout.LayoutFlags="All"  
               AbsoluteLayout.LayoutBounds="0,0,1,1">
      ...
  </StackLayout>

  <Button Text="gggggg"
          AbsoluteLayout.LayoutFlags="PositionProportional"   
          AbsoluteLayout.LayoutBounds="1,1,AutoSize,AutoSize"/>
</AbsoluteLayout>

以上重点是一切都在AbsoluteLayout范围内,这意味着您可以正确堆叠控件。其他重要项目是AbsoluteLayout.LayoutFlagsAbsoluteLayout.LayoutBoundsLayoutFlags上的LayoutBoundsStackLayout基本上只是告诉StackLayout它可以占据整个屏幕。 LayoutFlags上的LayoutBoundsButton表示Button需要位于右下角,并且可以自行调整大小。

答案 1 :(得分:1)

使其反向放置绝对布局内的堆栈布局以按预期工作

以下是示例代码

Button btnPlus = new Button()
{
    Text = "FAB"
    HeightRequest = 50,
    WidthRequest = 50
};

StackLayout stackLayout = new StackLayout
{
    Children = { STACK_CHILDRENS }
};

AbsoluteLayout absoluteLayout = new AbsoluteLayout();

AbsoluteLayout.SetLayoutFlags(btnPlus, AbsoluteLayoutFlags.PositionProportional);
AbsoluteLayout.SetLayoutBounds(btnPlus, new Rectangle(0.5, 0.95, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize));

AbsoluteLayout.SetLayoutFlags(stackLayout, AbsoluteLayoutFlags.All);
AbsoluteLayout.SetLayoutBounds(stackLayout, new Rectangle(0f, 0f, 1f, 1f));

absoluteLayout.Children.Add(btnPlus);
absoluteLayout.Children.Add(stackLayout);

Content = absoluteLayout;