如何在Xamarin.Forms RelativeLayout中水平居中视图?

时间:2014-10-23 09:01:10

标签: view relativelayout centering xamarin.forms

我想将标签水平居中放在RelativeLayout的{​​{1}}中。我试过这样的东西,但它不起作用:

Xamarin.Forms

我想在标签右侧放置第二个标签,而第一个标签水平居中。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:6)

当您执行 RelativeLayouts 时,您可以指定约束

要实现您的目标,首先需要使用 RelativeToParent 约束,然后使用 RelativeToView 约束,用于附加在第一个视图右侧的第二个标签

第一个视图将在整个页面中水平居中,第二个标签连接 relative 到第一个视图之后。

以下示例显示了这一点: -

RelativeLayout objRelativeLayout = new RelativeLayout();

Label objLabel1 = new Label();
objLabel1.BackgroundColor = Color.Red;
objLabel1.Text = "This is a label";
objLabel1.WidthRequest = 300;
objRelativeLayout.Children.Add(objLabel1,
    xConstraint: Constraint.RelativeToParent((parent) =>
    {
        return ((parent.Width - objLabel1.Width) / 2);
    }));

Label objLabel2 = new Label();
objLabel2.BackgroundColor = Color.Blue;
objLabel2.Text = "Hi";
objLabel2.WidthRequest = 100;
objRelativeLayout.Children.Add(objLabel2,
    xConstraint: Constraint.RelativeToView(objLabel1,
    new Func<RelativeLayout, View, double>((pobjRelativeLayout, pobjView) =>
    {
        return pobjView.X + pobjView.Width;
    })));

this.Content = objRelativeLayout;

更新1: -

如果您不想使用指定的宽度或内容属于未知大小,则必须通过调用触发重新布局视图需要根据您定义的约束重新定位时, RelativeLayout 上的 ForceLayout

下面的更新示例说明了这一点: -

StackLayout objStackLayout = new StackLayout()
{
    Orientation = StackOrientation.Vertical,
};

RelativeLayout objRelativeLayout = new RelativeLayout();
objStackLayout.Children.Add(objRelativeLayout);

Label objLabel1 = new Label();
objLabel1.BackgroundColor = Color.Red;
objLabel1.Text = "This is a label";
objLabel1.SizeChanged += ((o2, e2) =>
{
    objRelativeLayout.ForceLayout();
});
objRelativeLayout.Children.Add(objLabel1,
    xConstraint: Constraint.RelativeToParent((parent) =>
    {
        return ((parent.Width - objLabel1.Width) / 2);
    }));

Label objLabel2 = new Label();
objLabel2.BackgroundColor = Color.Blue;
objLabel2.Text = "Hi";
objRelativeLayout.Children.Add(objLabel2,
    xConstraint: Constraint.RelativeToView(objLabel1,
    new Func<RelativeLayout, View, double>((pobjRelativeLayout, pobjView) =>
    {
        return pobjView.X + pobjView.Width;
    })));

Button objButton1 = new Button();
objButton1.Text = "Test1";
objButton1.Clicked += ((o2, e2) =>
    {
        objLabel1.Text = "This is some other label text";
    });
objStackLayout.Children.Add(objButton1);

this.Content = objStackLayout;