![](/img/trans.png)
[英]How can i disable a button using a System.Timers.Timer in monodroid?
[英]monodroid Timer
我想在 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 線程更新 UI 實例 ( txv1
)。
您需要使用Activity.RunOnUiThread()從后台線程更新 UI:
private void OnTimeEvent(object source, ElapsedEventArgs e)
{
RunOnUiThread(delegate {
txv1.Text = count.ToString ();
count++;
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.