How is application orientation (landscape or portrait) locked?

元气小坏坏 提交于 2019-11-27 01:59:25

问题


I have tried to freeze orientation using:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Although the display stays in portrait orientation, the activity is still recreated. Any ideas how to solve this?

How can the orientation of the application be locked such that the activity is not recreated on orientation change?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/2663427/how-is-application-orientation-landscape-or-portrait-locked

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