Search code examples
c#multithreadingvisual-studiouser-interfacexamarin.android

how to make changes appear instantly in the user interface?


sorry for my bad English . i am new to xamarin android, i am facing a problem when trying to make changes in the user interface. For example last time i tried to change the background of a button when clicking it. But this doesn't happen until the end of the the click method.

    private void MainActivity_Click(object sender, EventArgs e)
    {

        ((Button)(sender)).SetBackgroundResource(Resource.Drawable.background);

        //other code to run

    }

I tried to do it in RunOnUiThread and BeginInvokeOnMainThread but it didn't work either. When debugging,i found that it actually made the change instantly but it does not appear on the app until the method is done.Also there is an event when the button state ispressed =true,and the button stay highlighted even after release,it stuck like that until the end of the method MainActivity_Click. Sorry again for my bad English. Solutions?


Solution

  • It seems your "other code to run" block the thread,you could try to use asynchronous tasks to handle these time-consuming operations.

    try below :

    private void MainActivity_Click(object sender, EventArgs e)
    {
    
        ((Button)(sender)).SetBackgroundResource(Resource.Drawable.background);
    
        DoAsyncTask();
    
    }
    
    
    public async void DoAsyncTask()
    {
    
      await Task.Run(() =>
       {
         //other code to run
       });
    
    }
    

    You could look at Asynchronous programming