2

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();
         };
    }
SushiHangover
  • 73,120
  • 10
  • 106
  • 165

1 Answers1

2

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());
};
FreakyAli
  • 13,349
  • 3
  • 23
  • 63
SushiHangover
  • 73,120
  • 10
  • 106
  • 165