[英]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 秒钟。 我尝试使用的代码如下:
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 立即恢复颜色
有谁知道如何解决这个问题?
您可以通过以下方式使用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文档。
看起来您正在调用由主线程执行的方法中的语句,该主线程也负责渲染。 这意味着你的陈述
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.