You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android设置RequestedOrientation未触发MainDisplayInfoChanged事件问询

问题根因

Android平台下,通过代码主动设置RequestedOrientation修改屏幕方向时,Xamarin.Essentials的DeviceDisplay.MainDisplayInfoChanged事件仅响应物理传感器触发的方向变更,代码触发的方向变更默认不会触发该事件,这是Essentials库在安卓平台的实现机制导致的,iOS系统会统一回调所有方向变更因此无异常。


解决方案

方案1:主动调用业务逻辑(最便捷,无需修改平台代码)

不需要依赖MainDisplayInfoChanged事件处理全屏逻辑,在切换方向的方法中直接执行对应操作即可,修改共享层的ToggleFullScreen方法:

private void VideoControlView_ToggleFullScreen(object sender, EventArgs e)
{
    var orientationService = DependencyService.Get<IOrientationService>();
    if (_isFullScreen)
    {
        orientationService.SetOrientationToPortrait();
        // 主动触发竖屏全屏逻辑
        _ = DisplayVideoFullScreen(false);
    }
    else
    {
        orientationService.SetOrientationToLandscape();
        // 主动触发横屏全屏逻辑
        _ = DisplayVideoFullScreen(true);
    }
    _isFullScreen = !_isFullScreen;
}

方案2:安卓端监听配置变更,全局响应方向变化(适合多页面需要统一处理方向变更的场景)

  1. 先确保MainActivity已配置配置变更监听属性,避免方向切换时Activity重启:
[Activity(Label = "你的应用名称", 
    ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode,
    ScreenOrientation = ScreenOrientation.Portrait)]
public class MainActivity : FormsAppCompatActivity
{
    // 原有代码保持不变
}
  1. 重写MainActivity的OnConfigurationChanged方法,通过MessagingCenter通知共享层方向变更:
protected override void OnConfigurationChanged(Configuration newConfig)
{
    base.OnConfigurationChanged(newConfig);
    // 发送方向变更消息
    MessagingCenter.Send("Global", "OrientationChanged", DeviceDisplay.MainDisplayInfo);
}
  1. 共享层页面订阅消息,替换原有的MainDisplayInfoChanged事件监听:
// 页面OnAppearing中注册订阅
protected override void OnAppearing()
{
    base.OnAppearing();
    MessagingCenter.Subscribe<string, DisplayInfo>("Global", "OrientationChanged", async (sender, displayInfo) =>
    {
        if (AutoRotateDisabled) return;
        await DisplayVideoFullScreen(displayInfo.Orientation == DisplayOrientation.Landscape);
    });
}

// 页面OnDisappearing中取消订阅,避免内存泄漏
protected override void OnDisappearing()
{
    base.OnDisappearing();
    MessagingCenter.Unsubscribe<string, DisplayInfo>("Global", "OrientationChanged");
}

额外优化建议

修改安卓端OrientationService的方向枚举,使用带传感器的配置,避免固定死方向:

public void SetOrientationToLandscape()
{
    ((Activity)Forms.Context).RequestedOrientation = ScreenOrientation.SensorLandscape;
}

public void SetOrientationToPortrait()
{
    ((Activity)Forms.Context).RequestedOrientation = ScreenOrientation.SensorPortrait;       
}

这样切换后用户物理翻转手机时,横/竖屏还能自动适配朝向。

内容的提问来源于stack exchange,提问作者HtpaaPeterH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 09:54:04