所以我创建了一个显示倒计时从3到0的应用程序,用户可以点击重试,这将再次从3开始到0。我有tvTimer(TextView)显示倒数计时器。
代码工作正常但有时滞后/延迟,例如
当onCreate时,tvTimer.Text将显示3,2,1,0,但是当我单击Retry按钮时,有时会显示3,2,2,0。
你认为它是因为RunOnUIThread吗?
继承我的代码
int CountSeconds;
Button retry;
TextView tvTimer;
System.Timers.Timer aTimer = new System.Timers.Timer();
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Pagee);
tvTimer = FindViewById<TextView>(Resource.Id.tvTimer);
retry = FindViewById<Button>(Resource.Id.retry);
aTimer.Interval = 1000;
aTimer.Elapsed += OnTimedEvent;
play_timer();
retry.Click += Retry_Click;
}
public void play_timer()
{
CountSeconds = 3;
aTimer.Start();
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
RunOnUiThread(() => { tvTimer.Text = Convert.ToString(CountSeconds );});
CountSeconds = CountSeconds - 1;
if (CountSeconds == 0)
{
CountSeconds = 3;
aTimer.Stop();
}
private void Retry_Click(object sender, EventArgs e)
{
play_timer();
}
谢谢!!!
答案 0 :(得分:0)
如果你编写的代码运行在不同的线程上,比如这里
android {
packagingOptions {
exclude 'META-INF/DEPENDENCIES.txt'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/notice.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/dependencies.txt'
exclude 'META-INF/LGPL2.1'
}
}
这意味着这些部分中的任何一个都可以先运行,或者它们甚至可以在多核/ CPU系统上同时运行。例如,如果RunOnUiThread(() => { tvTimer.Text = Convert.ToString(CountSeconds );});
CountSeconds = CountSeconds - 1;
为3,则您可以在文本框中获得3或2。
为了确保事情以更可重复的顺序发生,您可以重新排序这些内容并将CountSeconds
移动到方法的末尾。然后你可以确定减法和检查零是先发生,然后才设置文本框。
您还可以将调用内的整个逻辑移动到UI线程中,以便它在同一个线程中立即发生,例如:
RunOnUiThread