问题描述
private async void moveMessage()
{
movingLabel = new Label();
movingLabel.HorizontalTextAlignment = TextAlignment.Center;
stackLayoutContainingMovingText.Children.Add(movingLabel);
Animation animation = new Animation();
double height = Application.Current.MainPage.Height;
movingLabel.Text = "MESSAGE";
animation.Commit(movingLabel,"animation",20,Easing.Linear,(d,f) =>
{
movingLabel.Translateto(0,height,Easing.Linear);
movingLabel.Translateto(0,-height,2000,Easing.Linear);
});
await Task.Delay(2000);
stackLayoutContainingMovingText.Children.Remove(movingLabel);
}
每次单击按钮时,我都会调用此方法。 这将为文本标签设置动画,使其从屏幕的底部移动到顶部。
由于某种原因,我必须创建一个新标签并将其添加到stacklayout子级中,因为如果不这样做,该动画将只发生一次且不会重复。
当前,这种代码可以工作,但是在动画过程中,它会将页面上的所有控件向上推然后向下推。 我还希望能够多次按下按钮,这应该允许多个标签同时向上移动动画。
解决方法
但是在动画过程中它会将页面上的所有控件向上推然后向下推。
由于单击按钮时,标签是在按钮下方创建的。这就是为什么页面上所有控件都向上。动画之后,新标签被删除。所以下一页。
在xaml中创建标签,并使用代码进行上下滚动。
xaml:
<StackLayout x:Name="stackLayoutContainingMovingText">
<!-- Place new controls here -->
<Label
x:Name="movingLabel"
HorizontalOptions="Center"
Text="Welcome to Xamarin.Forms!"
VerticalOptions="EndAndExpand" />
<Button
HorizontalOptions="EndAndExpand"
x:Name="btn_Move"
Clicked="btn_Move_Clicked"
Text="Move" />
</StackLayout>
背后的代码:
private void btn_Move_Clicked(object sender,EventArgs e)
{
moveMessage();
}
private async void moveMessage()
{
double up = Application.Current.MainPage.Height;
double down = movingLabel.Height;
await movingLabel.TranslateTo(0,-up,2000,Easing.Linear);
await movingLabel.TranslateTo(0,down,Easing.Linear);
}
截屏:
更新:
如果要取消动画,可以使用ViewExtensions.CancelAnimations
。
ViewExtensions.CancelAnimations(movingLabel);
将取消按钮置于按钮中时,如下所示,它将停止当前动画。
private void btn_Cancel_Clicked(object sender,EventArgs e)
{
ViewExtensions.CancelAnimations(movingLabel);
}
截屏: