Xamarin.Forms不以android为中心布局

时间:2016-09-15 08:17:21

标签: layout xamarin.forms

我有3个标签 - 我希望将第二个标签居中,并为第一个和第三个标签填充相同尺寸的另一个空间。

相反,我发现在使用LayoutOption.FillANdExpand时需要考虑字符串

这是我的代码:

class MainPage : ContentPage
{
    public MainPage()
    {
        StackLayout a = new StackLayout();
        a.Orientation = StackOrientation.Horizontal;
        a.Spacing = 0;
        a.Padding = new Thickness(0, 0, 0, 0);
        a.HorizontalOptions = LayoutOptions.FillAndExpand;

        Label l1 = new Label { Text = "1111", HorizontalOptions = LayoutOptions.FillAndExpand, HorizontalTextAlignment = TextAlignment.Center, BackgroundColor = Color.Red, };
        Label l2 = new Label { Text = "2222222222222", HorizontalOptions = LayoutOptions.Center, HorizontalTextAlignment = TextAlignment.Center, BackgroundColor = Color.Gray };
        Label l3 = new Label { Text = "333333333333", HorizontalOptions = LayoutOptions.FillAndExpand, HorizontalTextAlignment = TextAlignment.Center, BackgroundColor = Color.Red };

        a.Children.Add(l1);
        a.Children.Add(l2);
        a.Children.Add(l3);
        Content = a;
    }
}

结果如下:enter image description here

我希望111和33333 ...标签具有相同的尺寸,并且2222标签位于我的页面中心...

2 个答案:

答案 0 :(得分:2)

您可以将Grid与3列一起使用:

<Grid>
 <Grid.ColumnDefinitions>
   <ColumnDefinition/>
   <ColumnDefinition Width="Auto"/>
   <ColumnDefinition/>
 </Grid.ColumnDefinitions>

 <Label Text="1111" TextColor="White" BackgroundColor="Red" />
 <Label Grid.Column="1" Text="2222222222222" TextColor="White" BackgroundColor="Gray" />
 <Label Grid.Column="2" Text="33333" TextColor="White" BackgroundColor="Red" />
</Grid>

答案 1 :(得分:0)

虽然Grid似乎可以正常工作,但它有点开销。您可以尝试以下布局选项:

      Label l1 = new Label { Text = "1111", HorizontalOptions = LayoutOptions.StartAndExpand, HorizontalTextAlignment = TextAlignment.Center, BackgroundColor = Color.Red, };
      Label l2 = new Label { Text = "2222222222222", HorizontalOptions = LayoutOptions.Center, HorizontalTextAlignment = TextAlignment.Center, BackgroundColor = Color.Gray };
      Label l3 = new Label { Text = "333333333333", HorizontalOptions = LayoutOptions.EndAndExpand, HorizontalTextAlignment = TextAlignment.Center, BackgroundColor = Color.Red };