How is application orientation (landscape or portrait) locked?

前端 未结 4 1096
春和景丽
春和景丽 2020-12-09 05:18

I have tried to freeze orientation using:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Although the display stays in

相关标签:
4条回答
  • 2020-12-09 05:38

    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.

    0 讨论(0)
  • 2020-12-09 05:38

    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

    0 讨论(0)
  • 2020-12-09 05:42

    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.

    0 讨论(0)
  • 2020-12-09 05:55

    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.

    0 讨论(0)
提交回复
热议问题