如何在 Android 中禁用横屏模式?
androidapps/applicationsmobile development
Android 支持纵向和横向两种屏幕方向。我们可以在 Android 应用程序中禁用屏幕方向。本示例演示了 如何在 Android 中禁用横屏模式。
步骤 1 − 在 Android Studio 中创建一个新项目,前往"文件"->"新建项目",并填写所有必填信息以创建新项目。
步骤 2 − 将以下代码添加到 res/layout/activity_main.xml。
<?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:background = "#dde4dd"> <EditText android:id = "@+id/editText" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> </LinearLayout>
上面的代码包含线性布局和文本编辑。它将支持横向和纵向布局,如下所示 -

上面的输出显示了横向模式

以上输出表示的是纵向模式。
要禁用横向模式,需要在 manifest.xml 中添加 screenOrientation 标签,如下所示 -
<?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity" android:screenOrientation = "portrait"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
在上面的代码中,我们将 screenOrientation 设置为 portrait,这意味着 MainActivity 将仅支持纵向模式。如果您想开发纵向模式的应用程序,请在 application 标签中添加 screenOrientation。
让我们尝试运行您的应用程序。假设您已将实际的 Android 移动设备连接到电脑。要从 Android Studio 运行该应用程序,请打开项目的某个 Activity 文件,然后单击工具栏上的"运行"
图标。选择您的移动设备作为选项,然后检查您的移动设备是否显示您的默认屏幕 −

以上结果仅显示纵向模式。现在转动您的设备,它不会根据方向改变视图。

