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

Visual Studio 2019 Android项目setRequestedOrientation报错解决咨询

问题解决方案

1. 错误修复步骤

出现The name 'setRequestedOrientation' does not exist in the current context错误的核心原因是Xamarin.Android中采用C#命名规范,方法名应为驼峰式的SetRequestedOrientation(而非Java风格的小写开头),同时需要确保调用对象和命名空间正确:

  • 必须通过当前Activity实例(比如this)调用该方法,因为SetRequestedOrientation是Activity类的成员方法
  • 引入Android.Content.PM命名空间,才能使用ScreenOrientation枚举参数

修复后的代码示例:

using Android.App;
using Android.Content.PM; // 必须添加该命名空间
using Android.OS;

namespace YourAppNamespace
{
    [Activity(Label = "@string/app_name", MainLauncher = true)]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            // 锁定为竖屏,可替换为ScreenOrientation.Landscape锁定横屏
            this.SetRequestedOrientation(ScreenOrientation.Portrait);
        }
    }
}

2. Android版本兼容性说明

不需要放弃Android 4.4.x(API Level 19)的支持:

  • SetRequestedOrientation方法和基础的ScreenOrientation枚举(如Portrait、Landscape)从API Level 1就已存在,完全兼容Android 4.4
  • 仅部分细分方向枚举(如ScreenOrientation.LockPortrait)是API Level 23(Android 6.0)新增的,若只使用基础锁定逻辑,低版本不受影响

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 16:47:00