作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在 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));
最佳答案
当你在做 相对布局 你有 约束 您可以指定。
要实现您的目标,您需要使用 相对父级 约束 首先,然后是 相对 View 约束 对于附加在第一个 View 右侧的第二个标签。
然后第一个 View 将在整个页面水平居中,并附加第二个标签 亲戚 之后的第一个 View 。
以下示例显示了这一点:-
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;
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;
关于xamarin - 如何在 Xamarin.Forms RelativeLayout 中水平居中 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26524632/
我是一名优秀的程序员,十分优秀!