首页 > 解决方案 > 执行操作时为按钮设置动画 Xamarin Android

问题描述

我有一个按钮,它执行一个需要 3 秒的操作(从 API 读取数据并刷新屏幕)。执行操作时,我希望按钮旋转。我的问题是它在 3 秒操作完成后开始旋转......并且,它立即停止,因为它击中 ClearAnimation..

这是我的代码

this.refreshButton.Click += this.RefreshPendingOrders_Click;



 private void RefreshPendingOrders_Click(object sender, EventArgs e)
    {
        this.StartRotateAnimation();
        System.Threading.Thread.Sleep(3000);
        this.refreshButton.ClearAnimation();
    }

    private void StartRotateAnimation()
    {
        
            var pivotX = this.refreshButton.Width / 2;
            var pivotY = this.refreshButton.Height / 2;
            var animation = new RotateAnimation(0f, 360f, pivotX, pivotY)
            {
                Duration = 500,
                RepeatCount = 3
            };

            this.refreshButton.StartAnimation(animation);
    }

标签: c#androidxamarinxamarin.android

解决方案


问题是您正在调用Thread.Sleep(),如果 Click EventHandler 将在 UI 线程上发生。这意味着您正在阻塞负责运行动画 3 秒的 UI 线程。

您可以更改代码以使用 async/await 代替,例如:

private async void RefreshPendingOrders_Click(object sender, EventArgs e)
{
    this.StartRotateAnimation();
    await Task.Delay(3000);
    this.refreshButton.ClearAnimation();
}

推荐阅读