RelativeLayout
设置一次后,是否可以更改a的约束?
在文档中,我看到了类似的方法GetBoundsConstraint(BindableObject)
,但是我认为只有在拥有XAML文件的情况下才能使用它们。现在,我正在尝试通过代码来实现。null
如果我尝试我会得到
RelativeLayout.GetBoundsConstraint(this.label);
我发现的唯一方法是从布局中删除子级,然后再次添加新的约束。
例子:
public class TestPage : ContentPage
{
private RelativeLayout relativeLayout;
private BoxView view;
private bool moreWidth = false;
public TestPage()
{
this.view = new BoxView
{
BackgroundColor = Color.Yellow,
};
Button button = new Button
{
Text = "change",
TextColor = Color.Black,
};
button.Clicked += Button_Clicked;
this.relativeLayout = new RelativeLayout();
this.relativeLayout.Children.Add(this.view,
Constraint.Constant(0),
Constraint.Constant(0),
Constraint.Constant(80),
Constraint.RelativeToParent((parent) =>
{
return parent.Height;
}));
this.relativeLayout.Children.Add(button,
Constraint.RelativeToParent((parent) =>
{
return parent.Width / 2;
}),
Constraint.RelativeToParent((parent) =>
{
return parent.Height / 2;
}));
this.Content = this.relativeLayout;
}
private void Button_Clicked(object sender, EventArgs e)
{
double width = 0;
if(this.moreWidth)
{
width = 120;
}
else
{
width = 80;
}
var c= BoundsConstraint.FromExpression((Expression<Func<Rectangle>>)(() => new Rectangle(0, 0, width, this.Content.Height)), new View[0]);
RelativeLayout.SetBoundsConstraint(this.view, c);
this.relativeLayout.ForceLayout();
this.moreWidth = !this.moreWidth;
}
}
当前版本的Xamarin Forms正式不支持此功能。该RelativeLayout
容器只添加/删除其子女集合( -推测的性能,缓存解决约束)项目时重新计算限制。即使将各种约束实现为可绑定属性,但在更改时仍不会重新计算它们。
我认为这样做的目的是为了有一天遵守约束更新,这对于例如动画很有用,但目前看来并没有这样的效果。
但是,我查看了RelativeLayout的反编译源,并且有可能围绕它进行改编-但它可能不符合您的需求,具体取决于您需要多少功能以及约束定义的复杂程度。
请参见以下示例代码(关键部分是使用SetBoundsConstraint设置约束,该约束会覆盖添加的视图的内部计算边界-然后调用ForceLayout()
):
public partial class App : Application
{
public App ()
{
var label = new Label {
Text = "Test",
HorizontalTextAlignment = TextAlignment.Center,
VerticalTextAlignment = TextAlignment.Center,
BackgroundColor = Color.Silver
};
var layout = new RelativeLayout ();
layout.Children.Add (label,
Constraint.Constant (50),
Constraint.Constant (100),
Constraint.Constant (260),
Constraint.Constant (30));
MainPage = new ContentPage {
Content = layout
};
var fwd = true;
layout.Animate ("bounce",
(delta) => {
var d = fwd ? delta : 1.0 - delta;
var y = 100.0 + (50.0 * d);
var c = BoundsConstraint.FromExpression ((Expression<Func<Rectangle>>)(() => new Rectangle (50, y, 260, 30)), new View [0]);
RelativeLayout.SetBoundsConstraint(label, c);
layout.ForceLayout ();
}, 16, 800, Easing.SinInOut, (f, b) => {
// reset direction
fwd = !fwd;
}, () => {
// keep bouncing
return true;
});
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句