Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: listen for Orientation change?

Tags:

android

How would I listen for orientation change in Android? and do certain things when the user has switched to landscape?

like image 757
Skizit Avatar asked Jun 09 '11 13:06

Skizit


People also ask

What happens on orientation change Android?

When you rotate your device and the screen changes orientation, Android usually destroys your application's existing Activities and Fragments and recreates them. Android does this so that your application can reload resources based on the new configuration.

How do you know if orientation changes?

This example demonstrates how do I detect orientation change in layout in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How can we detect the orientation of the screen in Android?

int orientation = display. getOrientation(); Check orientation as your way and use this to change orientation: setRequestedOrientation (ActivityInfo.


2 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.

like image 97
ferostar Avatar answered Sep 28 '22 05:09

ferostar


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;  } 
like image 39
Huang Avatar answered Sep 28 '22 07:09

Huang