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

Android MAUI应用特定页面启用屏幕旋转功能的实现方法

实现Android MAUI特定页面允许横屏(全局已禁用)

你已经在MainActivity中全局锁定了竖屏,要让单个页面支持自动旋转,只需在目标页面的生命周期方法中动态修改Activity的屏幕方向即可,具体实现如下:

步骤1:在目标页面重写生命周期方法

打开需要允许横屏的页面代码(例如LandscapeAllowedPage.xaml.cs),添加以下代码:

using Microsoft.Maui.ApplicationModel;

namespace YourAppNameSpace;

public partial class LandscapeAllowedPage : ContentPage
{
    public LandscapeAllowedPage()
    {
        InitializeComponent();
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();

#if ANDROID
        // 获取当前Activity,启用自动旋转(跟随设备物理方向)
        var currentActivity = Platform.CurrentActivity;
        if (currentActivity != null)
        {
            currentActivity.RequestedOrientation = Android.Content.PM.ScreenOrientation.Sensor;
        }
#endif
    }

    protected override void OnDisappearing()
    {
        base.OnDisappearing();

#if ANDROID
        // 离开页面时恢复全局竖屏设置
        var currentActivity = Platform.CurrentActivity;
        if (currentActivity != null)
        {
            currentActivity.RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;
        }
#endif
    }
}

关键细节说明

  • ScreenOrientation.Sensor:允许设备根据物理方向自动切换横竖屏;如果只想限制为横屏(左右均可),可替换为ScreenOrientation.Landscape
  • 你已在MainActivity的ConfigurationChanges中声明了Orientation等参数,Activity会正确处理方向变化而不会重启
  • 页面返回或销毁时,OnDisappearing会触发,将屏幕方向恢复为全局竖屏,不影响其他页面的显示逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 10:31:09