【问题标题】:Change screen orientation in Android without reloading the activity在不重新加载活动的情况下更改 Android 中的屏幕方向
【发布时间】:2013-02-14 11:26:32
【问题描述】:

我想在运行我的 Android 应用时以编程方式更改方向,使用以下代码行:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);  
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);

到目前为止,它们都可以工作,但主要问题是当屏幕方向发生变化时,整个活动都会重新加载,而我不希望这样。可能吗?谢谢。

编辑:好的,在我发现我错过了什么之后。我还必须在 configChanges 属性中包含“screenSize”,所以有

android:configChanges="orientation|screenSize"

解决了整个问题。

【问题讨论】:

标签: android screen-orientation


【解决方案1】:

查看@luisfer 的编辑。对于 Android 3.2 及更高版本,您需要 BOTH

android:configChanges="orientation|screenSize"

http://developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange

【讨论】:

  • 这改变了我所有的问题,导航堆栈也一样。谢谢人
【解决方案2】:

你需要重写onSaveInstanceState(Bundle savedInstanceState)并将你想要改变的应用程序状态值写入Bundle参数

【讨论】:

  • +1,这是正确答案 => 他所问的是不可能的,只要使用这个解决方案,他就可以做他想做的事,只有 API 高于 13 android:configChanges="orientation|screenSize "
【解决方案3】:

在 AndroidManifest 文件中添加 android:configChanges="orientation" 用于您要处理此方向的活动

在活动中使用 onConfigurationChange 覆盖方法。做你想在方向改变中处理的任务。

【讨论】:

  • 谢谢,但还是不行。可能是因为我在活动中使用了Phonegap/HTML5?谢谢。
  • @RajShah 需要更多代码吗?你读过这个问题吗?标题怎么样?
【解决方案4】:

在这里回答:

Android, how to not destroy the activity when I rotate the device?

添加:

android:configChanges="orientation"

到你的 androidmanifest。

见:

http://developer.android.com/guide/topics/manifest/activity-element.html#config

【讨论】:

  • 谢谢,但还是不行。可能是因为我在活动中使用了Phonegap/HTML5?谢谢。
【解决方案5】:

调用此方法并设置清单文件

android:configChanges="orientation|screenSize|keyboardHidden"

public void onConfigurationChanged(Configuration newConfig) {
     super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 2014-01-10
    相关资源
    最近更新 更多