【问题标题】:In Xamarin, how can I change the background color of a button for just 1 second and return it again to its original color?在 Xamarin 中,如何将按钮的背景颜色更改 1 秒,然后再次将其恢复为原始颜色?
【发布时间】:2020-10-10 12:43:43
【问题描述】:

我正在 Xamarin 中开发一个小应用程序,我想在用户按下按钮时更改按钮的背景颜色只需 1 秒。我尝试使用的代码如下:

var auxColor = btnCancel.BackgroundColor;    // saving the original color (btnCancel is the button name)
btnCancel.BackgroundColor = Color.Red;       // changing the color to red
Task.Delay(1000).Wait();                     // waiting 1 second            
btnCancel.BackgroundColor = auxColor;        // restoring the original color

但我得到的是以下序列:

1- 保存原色
2- 等待 1 秒
3 将颜色更改为红色
4 立即恢复颜色

有人知道如何解决这个问题吗?

【问题讨论】:

    标签: c# xamarin background-color


    【解决方案1】:

    看起来您正在调用由主线程执行的方法中的语句,该主线程也负责渲染。这意味着你的陈述

    Task.Delay(1000).Wait();                     // waiting 1 second   
    

    阻止渲染,因此您的更改将不可见。

    有不同的方法可以解决您的问题,最简单的方法是使用异步方法,以允许 UI 线程在后台继续:

    private async void blink()
    {
        var auxColor = btnCancel.BackgroundColor;    // saving the original color (btnCancel is the button name)
        btnCancel.BackgroundColor = Color.Red;       // changing the color to red
        await Task.Delay(1000)                       // waiting 1 second            
        btnCancel.BackgroundColor = auxColor;        // restoring the original color
    }
    

    另一种可能的解决方案是在延迟完成后再次使用原始 (UI) 线程上下文设置原始颜色:

    var auxColor = btnCancel.BackgroundColor;        // saving the original color (btnCancel is the button name)
    btnCancel.BackgroundColor = Color.Red;           // changing the color to red
    Task.Delay(1000).ContinueWith((T) =>             // waiting 1 second  
        {
            btnCancel.BackgroundColor = auxColor;    // restoring the original color
        }, TaskScheduler.FromCurrentSynchronizationContext());
    

    【讨论】:

    • 非常感谢Fruchtzwerg。我也会按照你的方法。
    • 太棒了!!两种方法都很好用!非常感谢。
    【解决方案2】:

    您可以通过以下方式使用Device.StartTimer

    在您的按钮点击事件中:

    private void OnButtonClicked(object sender, EventArgs e)
    {                    
        var auxColor = btnCancel.BackgroundColor;    // saving the original color 
        btnCancel.BackgroundColor = Color.Red; 
    
        Device.StartTimer(TimeSpan.FromSeconds(1), () =>
        {
            btnCancel.BackgroundColor = auxColor;             
            return false;
        });
    }
    

    要与 UI 元素交互,您可以使用BeginInvokeOnMainThread,例如:

    Device.StartTimer (new TimeSpan (0, 0, 1), () =>
    {
        // do something every 1 second
        Device.BeginInvokeOnMainThread (() => 
        {
          // interact with UI elements
        });
        return true; // runs again, or false to stop
    });
    

    请参阅Device.StartTimer docs。

    【讨论】:

    • 非常感谢菲利克斯。我会试试你说的。
    • 太棒了!!你的方法也很有效。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 2023-04-07
    • 2016-02-04
    • 2020-12-24
    • 2017-08-31
    • 2013-04-12
    相关资源
    最近更新 更多