我正在使用Xamarin MessagingCenter实现设备定位检测器。我想要做的是从我的安卓项目中的MainActivity发送消息到我的.NET标准项目中的Singleton类实现。
如您所见,我重写了“OnConfigurationChanged(.)”方法在我的MainActivity内部和所有断点在我的IF语句中被击中时,我切换方向从景观到肖像。问题是,我较新地接收到了这些消息。在我的"OrientationHelper“中回调是较新的调用。
"OrientationHelper“在加载第一个页面时被实例化(对于那些会说我没有实例的人:)
MainActivity:
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接收消息的Singleton类:
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;
}
}
}OrientationChangedEventArgs:
public class OrientationChangedEventArgs : EventArgs
{
public Orientation Orientation { get; private set; }
public OrientationChangedEventArgs(Orientation orientation)
=> Orientation = orientation;
}发布于 2019-02-13 14:02:48
订阅和发送方法的定义如下
这两个调用中的第一个T参数应该匹配发送消息的类的类型。
MessagingCenter.Send<MyType, OrientationChangedEventArgs>(this, "OrientationContract"
, new OrientationChangedEventArgs(Orientation.Landscape));
MessagingCenter.Subscribe<MyType, OrientationChangedEventArgs>(this, "OrientationContract"
, s => DeviceOrientation = s.Orientation);https://stackoverflow.com/questions/54671908
复制相似问题