如何将布局方向固定为垂直方向?

80

如何将布局方向固定为纵向,并在运行时不允许从纵向切换到横向?

7个回答

163
在你的 AndroidMainfest.xml 文件中找到你想要锁定方向的活动标签,然后添加这个属性:
android:screenOrientation="portrait"

@AlekseyTimoshchenko 你能描述一下它为什么不工作吗? - parvus
3
当我在清单文件中加入android:screenOrientation="portrait"属性后,根据答案我仍然可以旋转屏幕。最终我在下一个步骤找到了解决方案,即在每个活动的onCreate()中添加这行代码:setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); - Sirop4ik
你好,能否看一下我的问题:https://dev59.com/3ND7oIgBc1ULPQZFVRsW - Merlin Jeyakumar

24

按照以下示例使用setRequestedOrientation()

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
setContentView(R.layout.main);

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

个人而言,我更喜欢这种方式。如果你想改变方向,这非常方便;否则,如果你只会将设备放在那个方向上,那就使用XML。 - Chris.Jenkins

16

在 Manifest 文件中的活动参数中

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.statepermit" android:versionCode="1" android:versionName="1.0">
    <application android:icon="@drawable/stateheader" android:label="@string/app_name">
        <activity android:name=".statepermit" android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar" android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-sdk android:minSdkVersion="7" />

</manifest>

android:screenOrientation="portrait"


3
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

之前

setContentView(R.layout.main);

3

2
在您的AndroidManifest.xml中只需在声明活动的位置编写以下内容,
如果您希望在垂直布局中使用,则使用以下代码。
android:screenOrientation="portrait"

如果您想使用横向布局,请使用以下代码:

android:screenOrientation="landscape"

2

如果您想要在项目中固定一个Activity的方向,您需要打开Manifest.xml文件,并在所需Activity的参数部分中添加以下内容(在第一个标签< activity…>结束之前):

android:screenOrientation="portrait" 如果您想要垂直固定方向

android:screenOrientation="landscape" 如果您想要水平固定方向


你好,你能帮我解决这个问题吗?https://dev59.com/3ND7oIgBc1ULPQZFVRsW - Merlin Jeyakumar
嗨,你能帮我解决这个问题吗?https://stackoverflow.com/questions/74940364/android-13-landscape-orientation-are-not-actually-landscape - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接