在Android中,我应该如何监听屏幕方向的变化?并且在用户切换到横屏时执行某些操作?
你有几个选择:
使用一个OrientationEventListener,它有一个名为onOrientationChanged的方法。
使用配置更改:
在你的清单文件中添加:
<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.
}
}
这是一个不错的教程。
public void onConfigurationChanged (Configuration newConfig)
在 Configuration
类中有一个整型常量 ORIENTATION_LANDSCAPE
和 ORIENTATION_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;
}
super.onConfigurationChanged(newConfig);
,以避免引起异常。 - Kyle Cleggandroid:configChanges="orientation"
。 - IgniteCoders从 Android 3.2 版本开始,你需要在androidmanifest文件中为特定活动添加"screenSize"。
因此,你在xml中声明的活动将变成:
<activity android:name=".ExampleActivity"
android:label="@string/app_name"
android:configChanges="orientation|screenSize">