目前,我有一个父Activity
,其方向可以是横向模式或纵向模式,具体取决于设备加速计。
它将启动一个孩子Activity
,其方向始终处于横向模式。
当用户退出子Activity
时,我父亲Activity
可以立即恢复其原始方向。
我尝试以下神话。它不起作用。
public class ParentActivity extends SherlockFragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
if (savedInstanceState == null) {
} else {
int orientation = savedInstanceState.getInt(ORIENTATION_KEY);
// **Orientation is completely detached from Accelerometer**
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
@Override
protected void onSaveInstanceState (Bundle savedInstanceState) {
// Calling super.onSaveInstanceState is important.
super.onSaveInstanceState(savedInstanceState);
// **Too late**
int orientation = getResources().getConfiguration().orientation;
savedInstanceState.putInt(ORIENTATION_KEY, orientation);
}
}
代码有两个问题
Activity
并且正在调用父Activity
的{{1}}时,获取的方向值始终是横向的,尽管父onSaveInstanceState
最初处于纵向模式。Activity
后,父setRequestedOrientation
方向将被修复,不再依赖于设备加速计。我的目的是在孩子Activity
退出后恢复父Activity
初始方向。之后,我们仍然可以通过旋转设备自由地使用父Activity
方向。答案 0 :(得分:1)
这是我的解决方案,它将解决太晚和方向与Accelerometer完全分离
private int orientationBeforeHistory = Integer.MIN_VALUE;
private void launchChildActivity() {
this.orientationBeforeHistory = Utils.getScreenOrientation(this.getActivity());
...
}
@Override
public void onSaveInstanceState (Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(ORIENTATION_BEFORE_HISTORY_KEY, this.orientationBeforeHistory);
}
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
if (savedInstanceState != null) {
final int orientationBeforeHistory = savedInstanceState.getInt(ORIENTATION_BEFORE_HISTORY_KEY);
if (Integer.MIN_VALUE != orientationBeforeHistory) {
final Activity activity = getActivity();
activity.setRequestedOrientation(orientationBeforeHistory);
// Key step for not locking screen orientation.
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
}
}
要获得当前定位,请参阅How do I get the CURRENT orientation (ActivityInfo.SCREEN_ORIENTATION_*) of an Android device?