Ioannis Dontas
Ioannis Dontas

Reputation: 659

How to change a TextView every second in Xamarin Android

I am trying to refresh a TextView every second (after a Button Click) in Xamarin Android using the following code (simplified):

void OnClick_Start(object sender, EventArgs ea)
    {
        RunOnUiThread(() =>
        {
            txtTest.Text = "Starting";
            Thread.Sleep(1000);
            txtTest.Text = "1000";
            Thread.Sleep(1000);
            txtTest.Text = "2000";
            Thread.Sleep(1000);
            txtTest.Text = "3000";
            Thread.Sleep(1000);
            txtTest.Text = "4000";
        });
    }

But I get only displayed the last value "4000" after 4 secs and not the intermediate values.

I have also used the following code with the same results

void OnClick_Start(object sender, EventArgs ea)
    {
        new Thread(new ThreadStart(() =>
        {
            RunOnUiThread(() =>
            {
                txtTest.Text = "Starting";
                Thread.Sleep(1000);
                txtTest.Text = "1000";
                Thread.Sleep(1000);
                txtTest.Text = "2000";
                Thread.Sleep(1000);
                txtTest.Text = "3000";
                Thread.Sleep(1000);
                txtTest.Text = "4000";
            });
        })).Start();
    }

How can I get the result that I want?

Upvotes: 1

Views: 647

Answers (1)

Marek Rzeźniczek
Marek Rzeźniczek

Reputation: 484

You can wait one second on other thread - non UI.

For example:

async void OnClick_Start(object sender, EventArgs ea)
{
    txtTest.Text = "Starting";
    await System.Threading.Tasks.Task.Delay(1000);
    RunOnUiThread(() =>   { txtTest.Text = "1000"; }
    await System.Threading.Tasks.Task.Delay(1000);
    RunOnUiThread(() =>   { txtTest.Text = "2000"; }
    await System.Threading.Tasks.Task.Delay(1000);
    RunOnUiThread(() =>   { txtTest.Text = "3000"; }
    await System.Threading.Tasks.Task.Delay(1000);
    RunOnUiThread(() =>   { txtTest.Text = "4000";}
}

Upvotes: 2

Related Questions