How is application orientation (landscape or portrait) locked?

廉价感情. 提交于 2019-11-28 07:39:28

First, don't use setRequestedOrientation() if you can avoid it. Use the android:screenOrientation attribute in your <activity> manifest element instead.

Second, you will also need android:configChanges="keyboardHidden|orientation" in your <activity> manifest element to prevent the destroy/recreate cycle.

A more specific example of the activity section of the AndroidManifest.xml for portrait orientation:

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:configChanges="keyboardHidden|orientation|screenSize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

Where android:screenOrientation sets the initial orientation and android:configChanges voids the events that triggers the corresponding lifecycle methods on screen changes.

Try this:

1.- Set the desired screen orientation in your AndroidManifest.xml

android:screenOrientation="portrait|landscape"

It should look like this:

    <application
    android:allowBackup="true"
    android:icon="~icon path~"
    android:label="~name~"
    android:supportsRtl="true"
    android:screenOrientation="portrait"
    android:theme="@style/AppTheme">
    </application>

2.- Add this to your onCreate void(or wherever you want) in your java Activity File(Example: "MainActivity.java"):

super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);

It should look like this:

protected void onCreate(Bundle savedInstanceState) {
    super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);}

Now the screen wont move even if the Screen Rotation is on in the Device.

The best solution is to use the saved instance. If you are locking the the screen orientation then it means you are forcing the user to use the app according to constraints set by you. So always use onSaveInstanceState. Read this link: http://developer.android.com/training/basics/activity-lifecycle/recreating.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!