【问题标题】:Reusable label animation messing up stack layout可重复使用的标签动画弄乱了堆栈布局
【发布时间】:2020-09-08 05:09:18
【问题描述】:
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, 0, Easing.Linear, (d, f) =>
        {
            movingLabel.TranslateTo(0, height, 0, Easing.Linear);
            movingLabel.TranslateTo(0, -height, 2000, Easing.Linear);
        });

        await Task.Delay(2000);

        stackLayoutContainingMovingText.Children.Remove(movingLabel);

    }

每次单击按钮时我都会调用此方法。 这将为文本标签设置动画,使其从屏幕底部移动到顶部。

出于某种原因,我必须创建一个新标签并将其添加到 stacklayout 子项中,因为如果我不这样做,这个动画只会发生一次并且不会重复。

目前这种代码可以工作,但它会在动画期间将页面上的所有控件向上和向下推送。 我还希望能够多次按下按钮,这应该允许多个标签同时向上动画。

【问题讨论】:

  • 我认为当您在堆栈布局中添加标签时,其他控件会向上移动,因为它包含的空间。你能分享你的 XAML 吗?

标签: c# xamarin animation label


【解决方案1】:

但它会在动画期间将页面上的所有控件向上推然后向下推。

因为当你点击按钮时,标签是在按钮下创建的。这就是为什么页面上的所有控件都向上了。并且在动画之后,新标签被移除了。所以页面向下。

在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, 2000, Easing.Linear);
    }

截图:

更新:

如果要取消动画,可以使用ViewExtensions.CancelAnimations

 ViewExtensions.CancelAnimations(movingLabel);

当你把这个取消按钮点击如下时,它会停止当前的动画。

   private void btn_Cancel_Clicked(object sender, EventArgs e)
    {
        ViewExtensions.CancelAnimations(movingLabel);
    }

截图:

【讨论】:

  • 谢谢,这解决了部分问题,但是如果你点击移动按钮太快,它会完全破坏动画,直到你重新加载页面才会起作用。如果在动画运行时单击按钮,有没有办法取消动画并让它重新开始?
猜你喜欢
  • 2014-11-19
  • 1970-01-01
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 2016-07-16
相关资源
最近更新 更多