开发者

Android: listen for Orientation change?

开发者 https://www.devze.com 2023-03-11 22:16 出处:网络
How would I listen for orientation change in Android? and do certain things when the user has switched to开发者_如何学Python landscape?You have a couple of choices:

How would I listen for orientation change in Android? and do certain things when the user has switched to开发者_如何学Python landscape?


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;

}


As of Android 3.2, you also need to add "screenSize" in androidmanifest for specific activity

So your activity declaration in xml will become

<activity android:name=".ExampleActivity"
    android:label="@string/app_name"
    android:configChanges="orientation|screenSize">
0

精彩评论

暂无评论...
验证码 换一张
取 消