Reputation:
It's simple code that increases a number and shows it in a texView but it's not working and I don't know what is wrong with my code...
here is my code:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
TextView textView = FindViewById<TextView>(Resource.Id.textView1);
Timer timer1 = new Timer();
timer1.Interval = 1000;
timer1.Enabled = true;
timer1.Start();
timer1.Elapsed += (object sender, ElapsedEventArgs e) =>
{
x++;
textView.Text = x.ToString();
};
}
Upvotes: 2
Views: 98
Reputation: 74094
Since you are not using a SynchronizingObject, System.Timers.Timer
is calling Elapsed on a threadpool thread, thus you are not on the UI/Main thread (where UI updates need to be performed).
So use RunOnUiThread
to update your UI within the event:
timer1.Elapsed += (object sender, ElapsedEventArgs e) =>
{
x++;
RunOnUiThread(() => button.Text = x.ToString());
};
Upvotes: 2