How would I listen for orientation change in Android? and do certain things when the user has switched to landscape?
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.
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.
int orientation = display. getOrientation(); Check orientation as your way and use this to change orientation: setRequestedOrientation (ActivityInfo.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With