user3034944
user3034944

Reputation: 1741

Update UI in middle of thread execution c# android

I am currently migrating java code for my android app to C#. I want to update my UI in middle of thread execution.

Here is my java code:-

private Handler handler = new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(Message msg) {
      if (msg.what == MSG_SURFACE_CREATED) {
        contentWidth = 0;
        contentHeight = 0;
        requestLayout();
        return true;
      } else {
        Log.w("Unknown msg.what: " + msg.what);
      }
      return false;
    }
  });

And:-

void postChangedToView(final int indexInAdapter) {
    handler.post(new Runnable() {
        @Override
        public void run() {
            changedToView(indexInAdapter, true);
        }
    });
}

I have tried something like this in c# :-

private Android.OS.Handler handler = new Android.OS.Handler();

private class Callback : Android.OS.Handler.ICallback //inner class 
{

    ViewController fp;    //Create instance of outer class 
    public Callback(FViewController _fp) //pass the instance to constructor of inner class
    {
        fp = _fp;
    }
    #region ICallback implementation

    public bool HandleMessage (Message msg)
    {
        if (msg.What == MSG_SURFACE_CREATED)
        {
            contentWidth = 0;
            contentHeight = 0;

            fp.RequestLayout ();   

            return true;
        }
        else
        {
            Log.w("Unknown msg.what: " + msg.What);
        }
        return false;
        throw new NotImplementedException ();
    }
}

Here I cannot make an inline class of Handler.ICallBack

And:-

internal virtual void postChangedToView(int indexInAdapter) {
    handler.Post (Task.Run (()=> flippedToView (indexInAdapter,true)));
}

Here I get an error saying :-

Error CS1503: Argument 1: cannot convert from 'System.Threading.Tasks.Task' to 'System.Action' 

Upvotes: 0

Views: 264

Answers (1)

Hiệp Lê
Hiệp Lê

Reputation: 634

Handler.Post requires a System.Action parameter. You can create System.Action as below:

internal virtual void postFlippedToView(int indexInAdapter)
{
    Action action = () => flippedToView(indexInAdapter, true);
    handler.Post (action );
}

Upvotes: 1

Related Questions