将活动恢复到原始方向的正确方法

时间:2014-03-05 15:05:30

标签: android

目前,我有一个父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);
        }
    }

代码有两个问题

  1. 太晚 - 当启动横向广告素材Activity并且正在调用父Activity的{​​{1}}时,获取的方向值始终是横向的,尽管父onSaveInstanceState最初处于纵向模式。
  2. 方向与Accelerometer完全分离 - 调用Activity后,父setRequestedOrientation方向将被修复,不再依赖于设备加速计。我的目的是在孩子Activity退出后恢复父Activity初始方向。之后,我们仍然可以通过旋转设备自由地使用父Activity方向。

1 个答案:

答案 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?