Android: 如何监听屏幕方向变化?

33

在Android中,我应该如何监听屏幕方向的变化?并且在用户切换到横屏时执行某些操作?

3个回答

63

你有几个选择:

在你的清单文件中添加:

<activity android:name=".HelloAndroid"
    android:label="@string/app_name"
    android:configChanges="orientation">

在您的Activity中,重写 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.    
    }   
}

这是一个不错的教程


@ferostar 配置更改是否报告设备方向更改或UI方向更改?第一个似乎很清楚,因为它使用了传感器管理器。我不确定第二个。 - Mark13426
3
从API 13及更高版本开始,清单configChanges属性需要设置为:"orientation|screenSize"。详见该答案获取更多信息:https://dev59.com/AW035IYBdhLWcg3wGMLa。 - mohlman3

18
在你的Activity中,你可以重写这个方法来监听屏幕方向的变化并实现自己的代码。
public void onConfigurationChanged (Configuration newConfig)

Configuration 类中有一个整型常量 ORIENTATION_LANDSCAPEORIENTATION_PORTRAIT,因此您可以像这样检查新的配置:

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
黄 - 你的建议很好,只需做一个修改。你需要在方法开头添加 super.onConfigurationChanged(newConfig);,以避免引起异常。 - Kyle Clegg
是的,super调用是必要的。在Eclipse中,这行代码会自动添加。这就是为什么我省略了它。 - Huang
1
从未被调用:S。即使我在清单中放置了android:configChanges="orientation" - IgniteCoders
它从未被调用。在清单文件中添加 android:configChanges="orientation|screenSize" 后它就可以工作了。 - Irfan Raza

7

Android 3.2 版本开始,你需要在androidmanifest文件中为特定活动添加"screenSize"。

因此,你在xml中声明的活动将变成:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接