我面临一个奇怪的问题:我有一项活动,当方向改变为景观时,会启动另一项活动。问题是当我顺时针转动设备时,新活动处于反向位置。
要了解一些截图......
FirstActivity(以纵向模式运行):
当我逆时针转动设备时,我的第二个活动启动了,这一切都很有效:
如果我以纵向方向转动我的设备,第一个活动就会被调用,而且一切正常:我可以一次又一次地转动它,它总是有效。 问题是,当我顺时针转动我的设备时,我得到这个:
这里是代码:
第一项活动(glanceActivity):
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_glance_landscape);
setOrientationChangeListener();
}
private void setOrientationChangeListener() {
mOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL){
long changeStart = 0;
@Override
public void onOrientationChanged(int arg0) {
if (arg0 > 80 && arg0 < 280) {
if(changeStart == 0) {
changeStart = System.currentTimeMillis();
}
else if ((System.currentTimeMillis() - changeStart) > 1500) {
launchLandscapeActivity();
changeStart = 0;
}
}
else {
changeStart = 0;
}
}
};
if (mOrientationEventListener.canDetectOrientation()){
mOrientationEventListener.enable();
}
else{
finish();
}
}
private void launchLandscapeActivity() {
mOrientationEventListener.disable();
Intent intent = new Intent(GlanceActivity.this, GlanceLandscapeActivity.class);
startActivity(intent);
finish();
}
这是我的第二个活动(GlanceLandscapeActivity):
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_glance_landscape);
setOrientationChangeListener();
}
private void setOrientationChangeListener() {
mOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL){
long changeStart = 0;
@Override
public void onOrientationChanged(int arg0) {
if ((arg0 <= 360 && arg0 > 280) || (arg0 >= 0 && arg0 < 80)) {
if(changeStart == 0) {
changeStart = System.currentTimeMillis();
}
else if ((System.currentTimeMillis() - changeStart) > 1500) {
launchPortraitActivity();
changeStart = 0;
}
}
else {
changeStart = 0;
}
}
};
if (mOrientationEventListener.canDetectOrientation()){
mOrientationEventListener.enable();
}
else{
finish();
}
}
private void launchPortraitActivity() {
mOrientationEventListener.disable();
Intent intent = new Intent(GlanceLandscapeActivity.this, GlanceActivity.class);
startActivity(intent);
finish();
}
编辑:我忘了在manifest.xml中添加声明:
<activity
android:name=".GlanceActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:screenOrientation="portrait"
android:label="@string/title_activity_glance"
android:theme="@style/sectionsTheme" >
</activity>
<activity
android:name=".GlanceLandscapeActivity"
android:label="@string/title_activity_glance_landscape"
android:configChanges="orientation|keyboardHidden|screenSize"
android:screenOrientation="landscape"
android:theme="@android:style/Theme.Holo.Light.NoActionBar" >
</activity>