Use Timer

andre.luiz1987andre.luiz1987 André Luiz GomesBRMember

In my application uses a Timer to update the time. But the timer does not work, do you see the error?

protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle);

        // Create your application here
        SetContentView(Resource.Layout.RegisterPage);

        //Ajusta o horário atual 
        var txtCurrentHour = FindViewById<TextView>(Resource.Id.txtCurrentHour);
        var txtCurrentMinute = FindViewById<TextView>(Resource.Id.txtCurrentMinutes);

        txtCurrentHour.Text = DateTime.Now.Hour.ToString().PadLeft(2, '0');
        txtCurrentMinute.Text = DateTime.Now.Minute.ToString().PadLeft(2, '0');

         //Define o temporizador em 1 segundo
         objTimer.Interval = 1000;
         objTimer.Elapsed += new ElapsedEventHandler(TimerTick);
         objTimer.Enabled = true;
         //Inicia o temporizador
         objTimer.Start();
    }

    private void TimerTick(object source, ElapsedEventArgs e) 
    {           
        var txtCurrentHour = FindViewById<TextView>(Resource.Id.txtCurrentHour);
        var txtCurrentMinute = FindViewById<TextView>(Resource.Id.txtCurrentMinutes);

        txtCurrentHour.Text = e.SignalTime.Hour.ToString();
        txtCurrentMinute.Text = e.SignalTime.Minute.ToString();
    } 

Posts

  • YamilBrachoYamilBracho Yamil Bracho VEMember

    You have to uodate UI widgets from UI Main thread and in this case the timer is running in a separet thread so cahnge your code to :

    private void TimerTick(object source, ElapsedEventArgs e) {
    RunOnUiThread(delegate { var txtCurrentHour = FindViewById(Resource.Id.txtCurrentHour); var txtCurrentMinute = FindViewById(Resource.Id.txtCurrentMinutes);

                txtCurrentHour.Text = e.SignalTime.Hour.ToString();
                txtCurrentMinute.Text = e.SignalTime.Minute.ToString();
        });
    

    }

  • andre.luiz1987andre.luiz1987 André Luiz Gomes BRMember

    Tkhs!! This working now.

Sign In or Register to comment.