【问题标题】:RelativeLayout not positioning view on center horizontal when setting X Factor .5设置 X 因子 0.5 时,RelativeLayout 未将视图定位在水平中心
【发布时间】:2019-09-07 20:39:38
【问题描述】:

我正在处理RelativeLayout,我有三个BoxViewboxview3 我想使用Type=RelativeToView 来获取boxview2

boxview3XConstraint 我设置.5 仍然在左上角显示boxview3 为什么?如何在boxview2 之后获得boxview3

<RelativeLayout>
<BoxView x:Name="boxview1" BackgroundColor="#b87333"                 
         RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent,
         Property=Width,Factor=.5 }"                
         RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent,
         Property=Height, Factor=1}">
</BoxView>

<BoxView BackgroundColor="Red" x:Name="boxview2"                
         RelativeLayout.HeightConstraint="{ConstraintExpression ElementName=boxview1,
         Type=RelativeToView,Property=Height,Factor=.1}" 
         RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToView,
         ElementName=boxview1,Factor=1,Property=Width}"
         RelativeLayout.WidthConstraint="{ConstraintExpression   
         Type=RelativeToParent,Property=Width, Factor=0.1,Constant=-10}"
         RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToView,
         ElementName=boxview1,Property=Height,Factor=.4}">
</BoxView>

<BoxView BackgroundColor="Blue" x:Name="boxview3"
        RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToView,
        ElementName=boxview2, Property=Width,Factor=.5}">
</BoxView>

</RelativeLayout> 

注意:如果将XConstraint 指定为.5,我希望view 在屏幕中间,无论是水平方向。

输出截图:

【问题讨论】:

  • 不清楚您的问题是什么。你想让你的蓝色 boxview 在这里吗? prntscr.com/mu3yln
  • @DenseCrab -是的。我想要使​​用Type=RelativeToView 的红色框右侧的蓝色框,仅此而已。当我将 X 设为 0.5 时,我原以为蓝色框会出现在中间,但事实并非如此。谢谢。

标签: xaml xamarin xamarin.forms


【解决方案1】:

简短的回答是您无法在 Xaml 中指定要查找的 X 约束,您必须使用 C#。 RelativeLayout 中的所有元素都相对于整个 RelativeLayout 进行定位。

你现在的 Xaml 指定 boxview2 的宽度是 0.1*RelativeLayout.Width - 10,而 boxview3 的 X 坐标是它的一半,所以它将定位在距离左上角 0.05*RelativeLayout.width - 5 处,即就是你所看到的。

对于 Xaml 中的 RelativeLayout 约束,您可以使用视图左上角的 X 或 Y 中的 1 个,或者它的宽度或高度。要实现你想要的,你需要boxview2的右上角(或boxview2.X + boxview2.Width)。您必须在后面的 C# 代码中创建 boxview3,例如:

reelativeLayout.Children.Add (boxview3, Constraint.RelativeToView (boxview2, (parent, view) => {
        return view.X + view.Width;
    }),
    …   // other constraints
    ));

根据您的需要,您可能会发现其他容器更易于使用。

【讨论】:

    猜你喜欢
    • 2018-11-26
    • 1970-01-01
    • 2012-07-20
    • 2012-10-09
    • 2015-03-15
    • 2018-12-07
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    相关资源
    最近更新 更多