在线程执行c#android的过程中更新UI



我目前正在将android应用程序的java代码迁移到C#。我想在线程执行过程中更新我的UI。

这是我的java代码:-

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;
    }
  });

和:-

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

我在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 ();
    }
}

在这里,我无法创建Handler.ICallBack 的内联类

和:-

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

这里我得到一个错误说:-

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

Handler.Post需要一个System.Action参数。您可以按如下方式创建System.Action

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

最新更新