Thursday, November 10, 2011

Lock a screen in portrait mode without losing data

 

As I continue to progress in my Android education, I’m finding out how to make my apps work the way I want them to do.  In this case, I needed to prevent the screen from rotating.  I also forgot that Android calls the onCreatemethod every time you do this.  Here is how I fixed that,

 

I opened the AndroidManifest.xml file.  I added two lines of code:

android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation">

The first tells Android to keep the screen in portrait mode. 

The second tells Android that in the event the device is rotated or the keyboard is pulled out, do not execute the onCreate method.  Instead, keep going with what you currently have open. 

Below is how the code in my AndroidManifest XML file looks.  Notice that these elements are called on a per activity bases.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="
http://schemas.android.com/apk/res/android"
    package="com.mctexpert.android.orientation"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".OrientationActivity"
            android:screenOrientation="portrait"
            android:configChanges="keyboardHidden|orientation">
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

No comments:

Post a Comment