kao*_*ick 4 view centering xamarin xamarin.forms
我想将标签水平居中RelativeLayout放入Xamarin.Forms.我试过这样的东西,但它不起作用:
var label = new Label {HorizontalOptions = LayoutOptions.Center};
var rl = new RelativeLayout();
rl.Children.Add(label, Constraint.RelativeToParent((parent) => parent.Width / 2 - label.Width / 2));
Run Code Online (Sandbox Code Playgroud)
我想在标签的右侧放置第二个标签,而第一个标签水平居中.我怎样才能做到这一点?
当你正在做RelativeLayouts你有约束,你可以指定.
要实现您的目标,首先需要使用RelativeToParent Constraint,然后使用RelativeToView Constraint作为附加到第一个视图右侧的第二个标签.
然后,第一个视图将在整个页面上水平居中,然后相对于第一个视图附加第二个标签.
以下示例显示了这一点: -
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;
Run Code Online (Sandbox Code Playgroud)
更新1: -
如果您不想使用指定的宽度或内容大小未知的,那么你将有触发重新布局通过调用ForceLayout上的RelativeLayout时期(县)需要根据重新定位约束你有定义.
下面更新的例子说明了这一点: -
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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8437 次 |
| 最近记录: |