gpt4 book ai didi

android - 将 Activity 恢复到其原始方向的正确方法

转载 作者:行者123 更新时间:2023-11-29 01:44:42 25 4
gpt4 key购买 nike

目前,我有一个父级 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 启动时,父 ActivityonSaveInstanceState 被调用, 获取的方向值始终是横向的,尽管父级 Activity 最初处于纵向模式。
  2. 方向与加速度计完全分离 - 一旦调用 setRequestedOrientation,父 Activity 方向将固定,不再依赖于设备加速度计。我的 Intent 是在子级 Activity 退出后恢复父级 Activity 的初始方向。在那之后,我们仍然可以通过旋转设备自由地使用父 Activity 方向。

最佳答案

这是我的解决方案,它将解决太晚Orientation is completely detached from 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?

关于android - 将 Activity 恢复到其原始方向的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22201498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com