我目前正在将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 );
}