从Handler获取价值

时间:2016-09-26 12:05:56

标签: c# xamarin

我的应用中有一个嵌入式jar库。在OnCreate方法中,我必须实例化我的代码中看到的库。没有其他方法可以使用此库。 将调用Handler并且消息的结果可用,但是一旦可用,就没有机会将值ValueFromHandler带回OnCreate方法。 我的问题是:有没有人只是为了看看处理程序应该如何将值返回给调用者的小代码片段?

这是我的代码:

public class MainActivity : Activity{
JarLibrary jarlib;

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);         
    SetContentView(Resource.Layout.Main);
    jarlib = new JarLibrary(this, new JarHandler(), null);

    jarlib.Run(ValueFromHandler) //Here I would need the value back from the handler

}}

public class JarHandler : Handler
{
    public override void HandleMessage(Message msg)
    {
        switch (msg.What)
        {
            case jarlib.MessageStateChange:
                if (msg.Arg1 == jarlib.StateReadyToRun)
                {
                    ValueFromHandler = msg.Obj;
                    Console.WriteLine(ValueFromHandler); //Once this value "msg.Obj" is available I need to bring it back to the caller (On Create)
                    Toast.MakeText(Application.Context, "Ready to run", ToastLength.Short).Show();
                }
                break;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您收到邮件时可以选择回拨<Setter Property="Controls.Foreground" Value="{DynamicResource AccentSelectedColorBrush}" />

Action

您也可以采用不同的方式,并在public class MainActivity : Activity { JarLibrary jarlib; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); var handler = new JarHandler(); jarlib = new JarLibrary(this, handler, null); handler.OnHandleMessage = (s, o) => { jarlib.Run(o); }; } public class JarHandler : Handler { public Action<object> OnHandleMessage; public override void HandleMessage(Message msg) { switch (msg.What) { case jarlib.MessageStateChange: if (msg.Arg1 == jarlib.StateReadyToRun) { OnHandleMessage?.Invoke(this, msg.Obj); Console.WriteLine(ValueFromHandler); //Once this value "msg.Obj" is available I need to bring it back to the caller (On Create) Toast.MakeText(Application.Context, "Ready to run", ToastLength.Short).Show(); } break; } } } 类的构造函数中作为参数传入MainActivity。然后在JarHandler上设置一个属性,然后使用该值执行某些操作。