Himanshu Dwivedi
Himanshu Dwivedi

Reputation: 8174

Xamarin.Android: TextView text doesn't change after Task.Delay() c#

I am trying to change the text of a TextView after some delay. I have written a method which is called after some operation is performed.

public void Update()
{
      Task.Delay(10000).ContinueWith(t =>
        {
            dotsLoaderView.Hide(); // This works fine
            imgOverlay.Visibility = ViewStates.Gone;  // This works fine
            ll_Info.Visibility = ViewStates.Visible;  // This doesn't work
            txt_Info.Text = "Some mesage !";  // This doesn't work
        });
}

Where ll_info is the id of a linear layout which contains the textview of id txt_info. I have reviewed my layout.xml file, there is no collision in android:name tags, each and every id are different. As when I change the text of this textview from any other place, it works but when I am trying to change inside Task.Delay(), it's not working. Why?

Upvotes: 1

Views: 651

Answers (2)

Divins Mathew
Divins Mathew

Reputation: 3176

View updations must be done on UI thread. Try:

public void Update()
{
    Task.Delay(10000).ContinueWith(t =>
    {
        dotsLoaderView.Hide();
        RunOnUiThread(delegate
        {
            imgOverlay.Visibility = ViewStates.Gone;
            ll_Info.Visibility = ViewStates.Visible; 
            txt_Info.Text = "Some mesage !";
        });
    });
}

Upvotes: 1

Nkosi
Nkosi

Reputation: 247153

Update the method to use async to allow for easier continuation.

public async Task UpdateAsync() {
    await Task.Delay(10000);//Non blocking delay on other thread
    //Back on the UI thread
    dotsLoaderView.Hide();
    imgOverlay.Visibility = ViewStates.Gone;
    ll_Info.Visibility = ViewStates.Visible;
    txt_Info.Text = "Some mesage !";
}

and have it called in a raised event's handler

public async void Action(object sender, EventArgs e) {
    await UpdateAsync();
}

Or have every thing done in the event handler

private event EventHandler Update = delegate { };

private async void OnUpdate(object sender, EventArgs e) {
    await Task.Delay(10000);//Non blocking delay on other thread
    //Back on the UI thread
    dotsLoaderView.Hide();
    imgOverlay.Visibility = ViewStates.Gone;
    ll_Info.Visibility = ViewStates.Visible;
    txt_Info.Text = "Some mesage !";
}

You register the event handler with the event

Update += OnUpdate;

and directly after the operation is performed raise the event

Updated(this, EventArgs.Empty);

Upvotes: 1

Related Questions