【问题标题】:How to implement CountDownTimer Class in Xamarin C# Android? [closed]如何在 Xamarin C# Android 中实现 CountDownTimer 类? [关闭]
【发布时间】:2013-06-25 14:56:37
【问题描述】:

我是 Xamarin.Android 框架的新手。我正在研究倒数计时器,但无法像java CountDownTimer class 那样实现。任何人都可以帮我将以下 java code 转换为 C# Xamarin android 代码。

    bar = (ProgressBar) findViewById(R.id.progress);
    bar.setProgress(total);
    int twoMin = 2 * 60 * 1000; // 2 minutes in milli seconds

    /** CountDownTimer starts with 2 minutes and every onTick is 1 second */
    cdt = new CountDownTimer(twoMin, 1000) { 

        public void onTick(long millisUntilFinished) {

            total = (int) ((dTotal / 120) * 100);
            bar.setProgress(total);
        }

        public void onFinish() {
             // DO something when 2 minutes is up
        }
    }.start();

【问题讨论】:

  • 我已添加链接..感谢回复
  • 你能告诉我如何在 ui 线程 xamarin android 上运行此代码
  • 你试过什么?看起来您需要的类是 CountDownTimer,因此只需将该代码从 Java 移植到 C# 就很简单了
  • 我也碰巧遇到了这个问题。我们在 Java 上使用 CountDownTimer 的方式与 C# 语法允许我们做的方式完全不同。我在this gist 上实现了CountDownTimer 作为子类。请重新提出问题,以便我回答他的需求。 P.S.:我编辑了这个问题,以便更好地解释它并获得他需要转换的原始 Java 源代码。
  • 不知道为什么因为不清楚而关闭。这似乎很明显。

标签: c# android xamarin.android xamarin


【解决方案1】:

为什么不为此使用System.Timers.Timer

private System.Timers.Timer _timer;
private int _countSeconds;

void Main()
{
    _timer = new System.Timers.Timer();
    //Trigger event every second
    _timer.Interval = 1000;
    _timer.Elapsed += OnTimedEvent;
    //count down 5 seconds
    _countSeconds = 5;

    _timer.Enabled = true;
}

private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
{
    _countSeconds--;

    //Update visual representation here
    //Remember to do it on UI thread

    if (_countSeconds == 0)
    {
        _timer.Stop();
    }
}

另一种方法是启动异步Task,它内部有一个简单的循环,然后使用CancellationToken 取消它。

private async Task TimerAsync(int interval, CancellationToken token)
{
    while (token.IsCancellationRequested)
    {
        // do your stuff here...

        await Task.Delay(interval, token);
    }
}

然后开始

var cts = new CancellationTokenSource();
cts.CancelAfter(5000); // 5 seconds

TimerAsync(1000, cts.Token);

记得抓住TaskCancelledException

【讨论】:

  • 感谢您的回复,您能告诉我如何在 ui 线程 xamarin android 上运行此代码吗?
  • RunOnUiThread(() => { /* update UI here */ });
猜你喜欢
  • 1970-01-01
  • 2020-09-10
  • 1970-01-01
  • 2010-11-27
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多