pannila vitanage
pannila vitanage

Reputation: 89

why onCreate method runs when orientation changes each times

I need to stop an Activity from going through onCreate() over and over again when orientation changes.

I added the following code in my AndroidManifest.xml:

android:configChanges="orientation|keyboardHidden|screenSize"

And added the onConfigurationChanged() method to the Activity, but it still goes through the onCreate() method each time the orientation changes...

Upvotes: 0

Views: 363

Answers (2)

AADProgramming
AADProgramming

Reputation: 6345

    One of to stop an Activity from going through onCreate() over and over again when orientation changes, is to set Activity's Orientation 
in AndroidManifest.xml to say, "portrait" using below code.



<activity
                android:name="com.example.YourActivity"
                android:screenOrientation="portrait"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
</activity>

But this means, you are restricting Activity UI to be only supported for portrait mode which is not what user might be expecting.

And if we try with android:configChanges="orientation|screenSize", system should not recreate your Activity, excluding keyboardHidden.

Assuming that you are developing this your application targets API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), then you should also declare the "screenSize" configuration.

Upvotes: 0

shkschneider
shkschneider

Reputation: 18243

This is normal/correct behavior.

The orientation changes the layout of your Activity, so it's going through onCreate() once again (actually to let you adapt your UI to the new configuration -- portrait ain't landscape at all UI/UX wise).

Try to never use android:configChanges (from the Android Dev Guide); this only avoids the problem and is a bad habit.

Note: Using (android:configChanges) should be avoided and used only as a last-resort. Please read Handling Runtime Changes for more information about how to properly handle a restart due to a configuration change.

Learn Android lifecycles and how to save its states (to later restore it of course), by handling runtime changes the right way.

Upvotes: 5

Related Questions