我面临一个奇怪的问题:我有一个活动,当方向变为横向时会启动另一个活动。问题是当我顺时针转动我的设备时,新活动处于相反的位置。
一些截图可以理解...
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>