我有一个适用于 Android 的应用程序,我想强制平板电脑(sw600dp 和更高版本)以横向模式显示,而手机以纵向模式显示,所以我在我的 BaseActivity 类的 onCreate 中处理
boolean isTablet= getResources().getBoolean(R.bool.isTablet);
if (isTablet) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
还有我把“isTablet”放在bools.xml文件里面的方式
values 手机文件夹
<resources>
<bool name="isTablet">false</bool>
</resources>
values-sw600dp 适用于平板电脑
<resources>
<bool name="isTablet">true</bool>
</resources>
在我使用的 AndroidManifest 中
android:screenOrientation="nosensor"
只需确保禁用设备方向传感器即可。
我的方法似乎工作正常(平板电脑横向和手机纵向)但是当我在 Nexus 7 上运行我的应用程序时出现问题 - 我的 Activity 创建两次。这些步骤是:
- Hole Nexus 7 in Portrait(如果我横向拿着平板电脑就没问题)
- 然后运行应用
我发现问题出在 setRequestedOrientation() 方法(上面有 2 个步骤)。所以我不想再调用那个方法了。我尝试在 AndroidManifest 中设置方向,例如:
android:screenOrientation="@integer/orientation"
因为: SCREEN_ORIENTATION_LANDSCAPE = 0 SCREEN_ORIENTATION_PORTRAIT = 1
我在 integers.xml 文件中声明“方向”并将其放入
values 手机文件夹
<resources>
<integer name="orientation">1</integer>
</resources>
values-sw600dp 适用于平板电脑
<resources>
<integer name="orientation">0</integer>
</resources>
同样,我的方法往往工作正常但我发现 AndroidMenifest 只理解 values 文件夹中的“方向”,而不是 values-sw600dp 文件夹中的“方向”。我不希望我的 Activity 调用 2 次。你有这样的问题吗??你能解决吗?谢谢。
最佳答案
来自文档 setRequestedOrientation(int) :
If the activity is currently in the foreground or otherwise impacting the screen orientation, the screen will immediately be changed (possibly causing the activity to be restarted)
它没有被重新创建,它只是被重新启动以解决方向的变化。
因此只需将不应运行两次的功能移动到onCreate
即可。
关于android - 在横向模式下调用 setRequestedOrientation() 时创建了两次 Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26563797/