方向的激活开关更改了吗? [英] Switch activiy on orientation changed?
问题描述
旋转手机时如何切换到其他活动?
How can I switch to another activity when rotating the phone?
我的要求:
- 活动A和活动B仅是纵向
- Acitvity L仅用于风景
- 当将显示A或B的风景模式时,将启动L.当显示L的肖像时,将显示A或B.
我可以创建此行为,期望返回按钮.按下该按钮时,我要避免横向使用A/B或纵向使用L,这是我想避免的.
I can create this behaviour, expect for the back button. When it is pressed I'm either getting A/B in landscape or L in portrait, which I want to prevent.
我在做什么(活动A和B,但L相似)
What I'm doing (Activities A & B, but L is similar)
要在定向更改时触发活动调用:
To trigger the activity call on orientation change:
@Override
public void onConfigurationChanged(Configuration newConfig) {
int newOrientation = newConfig.orientation;
if (newOrientation == Configuration.ORIENTATION_LANDSCAPE) {
Intent intent = new Intent(this, ActivityL.class);
startActivity(intent);
}
super.onConfigurationChanged(newConfig);
}
我想要类似以下的内容.但是手动(重新)设置方向完全无法调用onConfigurationChanged():
I want something like the following. But manually (re)setting the orientation prevents onConfigurationChanged() from being called at all:
@Override
public void onResume(){
super.onResume();
int currentOrientation = this.getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
当然,如果我在其他生命周期方法或onCreate(...)中执行此操作,也会发生同样的情况.
On course the same happens if I do it in other lifecycle methods or onCreate(...).
所有活动都有:
android:screenOrientation="sensor"
我还尝试使用旋转角度来模拟方向变化,但是这种行为似乎主要是随机的,甚至与正常的方向变化都不接近.
I also tried imitating the orientation change using the rotationg angle, but then the behavior seems mostly random and not even close to the normal orientation change.
推荐答案
我想setRequestedOrientation()会覆盖我在AndroidManifest中定义的内容:
I suppose setRequestedOrientation() overrides what I had defined in the AndroidManifest:
android:screenOrientation="sensor"
我需要将其重置为传感器以恢复自动方向更改:
I need to reset it to sensor to get the automated orientation changes back:
@Override
public void onConfigurationChanged(Configuration newConfig) {
int newOrientation = newConfig.orientation;
if (newOrientation == Configuration.ORIENTATION_LANDSCAPE) {
Intent intent = new Intent(this, ActivityL.class);
startActivity(intent);
}
super.onConfigurationChanged(newConfig);
// Reset to sensor:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
我对在onConfigurationChanged(..)中调用它感到惊讶,因为该方法不再通过方向更改来调用.但是我想当活动恢复时(按下后退按钮时),配置会以其他方式更改.
I'm a bit surprised that calling it within onConfigurationChanged(..) works, since that method is no longer called by orientation changes. But I guess the configuration is changed in some other way when the activity is resumed(when back button is pressed).
这篇关于方向的激活开关更改了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!