How would I listen for orientation change in Android? and do certain things when the user has switched to landscape?
3 Answers
You have a couple of choices:
Use an OrientationEventListener, which has a method called onOrientationChanged.
Use config changes:
In your Manifest, put:
<activity android:name=".HelloAndroid" android:label="@string/app_name" android:configChanges="orientation"> And, in your Activity, override onConfigurationChanged:
@Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); int newOrientation = newConfig.orientation; if (newOrientation == Configuration.ORIENTATION_LANDSCAPE) { // Do certain things when the user has switched to landscape. } } Here is a good tutorial about it.
3 Comments
Mark13426
@ferostar Do config changes report device orientation change or ui orientation change? The first one seems clear since it's using the sensor manager. I wasn't sure about the second one.
mohlman3
As of API level 13 and up, the manifest configChanges attribute needs to be: "orientation|screenSize". See this answer for more info: stackoverflow.com/questions/5620033/…
Derek K
There is another way to observe screen orientation globally, without the need for
configChanges in Activities: getApplicationContext().registerComponentCallbacks and override onConfigurationChanged method.In your activity, you can override this method to listen to Orientation Change and implement your own code.
public void onConfigurationChanged (Configuration newConfig) The Configuration Class has an int constant ORIENTATION_LANDSCAPE and ORIENTATION_PORTRAIT, there for you can check the newConfig like this:
super.onConfigurationChanged(newConfig);
int orientation=newConfig.orientation; switch(orientation) { case Configuration.ORIENTATION_LANDSCAPE: //to do something break; case Configuration.ORIENTATION_PORTRAIT: //to do something break; } 4 Comments
Kyle Clegg
Huang - your suggestion works well, with one edit. You need to add
super.onConfigurationChanged(newConfig); at the beginning of the method to avoid causing an exception.Huang
yes,the super call is neccessary. in eclipse,this line will be automatically added.That's why I omitted.
IgniteCoders
Never called :S. Even if i put
android:configChanges="orientation" in manifestIrfan Raza
It never called. Adding this on manifest made it work : android:configChanges="orientation|screenSize"