我如何在Android中听取方向更改?并在用户切换到横向时执行某些操作?
答案 0 :(得分:43)
您有几个选择:
使用OrientationEventListener,其中有一个名为onOrientationChanged的方法。
使用配置更改:
在你的清单中,放:
<activity android:name=".HelloAndroid"
android:label="@string/app_name"
android:configChanges="orientation">
并且,在您的活动中,覆盖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.
}
}
关于它,这是一个很好的tutorial。
答案 1 :(得分:17)
在您的活动中,您可以覆盖此方法以收听方向更改并实施您自己的代码。
public void onConfigurationChanged (Configuration newConfig)
Configuration
类有一个int常量ORIENTATION_LANDSCAPE
和ORIENTATION_PORTRAIT
,你可以在这里查看newConfig:
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;
}
答案 2 :(得分:5)
从 Android 3.2 开始,您还需要在androidmanifest中为特定活动添加“ screenSize ”
因此,您在xml中的活动声明将变为
<activity android:name=".ExampleActivity"
android:label="@string/app_name"
android:configChanges="orientation|screenSize">