0

我正在使用 Xamarin MessagingCenter 实现设备方向检测器。我想做的是将消息从我的 Android 项目中的 MainActivity 发送到我的 .NET Standart 项目中的 Singleton 类实现。

如您所见,我在 MainActivity 中重写了“OnConfigurationChanged(...)”方法,并且当我将方向从横向切换到纵向时,所有断点都在我的 IF 语句中被命中。问题是我更新收到这些消息。我的“OrientationHelper”中的回调是较新的。

“OrientationHelper”在第一页加载时被实例化(对于那些会说我没有实例的人:))

主要活动:

public override void OnConfigurationChanged(Android.Content.Res.Configuration newConfig)
{
    base.OnConfigurationChanged(newConfig);

    if (newConfig.Orientation == Android.Content.Res.Orientation.Landscape)
        MessagingCenter.Send(this, "OrientationContract"
            , new OrientationChangedEventArgs(Orientation.Landscape));

    else if (newConfig.Orientation == Android.Content.Res.Orientation.Portrait)
        MessagingCenter.Send(this, "OrientationContract"
            , new OrientationChangedEventArgs(Orientation.Portrait));
}

将从 MainActivity 接收消息的单例类:

public class OrientationHelper
{
    private OrientationHelper()
        => MessagingCenter.Subscribe<OrientationChangedEventArgs>(this, "OrientationContract"
            , s => DeviceOrientation = s.Orientation);

    private static OrientationHelper s_instace;
    public static OrientationHelper Instance
    {
        get
        {
            if (s_instace == null)
                s_instace = new OrientationHelper();
            return s_instace;
        }
    }

    private Orientation _deviceOrientation;
    public Orientation DeviceOrientation
    {
        get => _deviceOrientation;
        private set
        {
            if (_deviceOrientation == value)
                return;
            _deviceOrientation = value;
        }
    }
}

方向改变事件参数:

public class OrientationChangedEventArgs : EventArgs
{
    public Orientation Orientation { get; private set; }

    public OrientationChangedEventArgs(Orientation orientation)
        => Orientation = orientation;
}
4

1 回答 1

1

订阅和发送方法是这样定义的

  • 订阅(对象订阅者,字符串消息,Action 回调,TSender source = null)

  • 发送(TSender 发送者,字符串消息) 发送(TSender 发送者,字符串消息,TArgs args)

两个调用中的第一个T参数应该与发送消息的类的类型相匹配

MessagingCenter.Send<MyType, OrientationChangedEventArgs>(this, "OrientationContract"
        , new OrientationChangedEventArgs(Orientation.Landscape));

MessagingCenter.Subscribe<MyType, OrientationChangedEventArgs>(this, "OrientationContract"
        , s => DeviceOrientation = s.Orientation);
于 2019-02-13T14:02:48.033 回答