开发者

How is application orientation (landscape or portrait) locked?

I have tried to freeze orientation using:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Although the display stays in portrait orientation, the activity is still recr开发者_如何学Goeated. 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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜