我想在 Android 2.2 的 C# monodroid 程序中使用计时器,但它不起作用。
这是我的代码:
using System;
using System.Timers;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Util;
namespace MonoAndroidApplication1
{
[Activity(Label = "MonoAndroidApplication1", MainLauncher = true, Icon=drawable/icon")]
public class Activity1 : Activity
{
int count = 1;
TextView txv1;
System.Timers.Timer t1;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
txv1 = FindViewById<TextView>(Resource.Id.txv1);
DateTime dt = DateTime.Now;
txv1.Text = dt.ToShortTimeString();
t1 = new System.Timers.Timer(200);
t1.Elapsed += new ElapsedEventHandler(OnTimeEvent);
t1.Interval = 200;
t1.Enabled = true;
t1.Start();
}
private void OnTimeEvent(object source, ElapsedEventArgs e)
{
txv1.Text = count.ToString();
count++;
}
}
}
请帮我。
System.Timers.Timer
将在单独的(非 UI)线程上运行。因此,您的OnTimeEvent()
方法不正确,因为它将更新 UI 实例(txv1
) 来自非 UI 线程。
你需要使用Activity.RunOnUiThread()从后台线程更新 UI:
private void OnTimeEvent(object source, ElapsedEventArgs e)
{
RunOnUiThread(delegate {
txv1.Text = count.ToString ();
count++;
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)