相关疑难解决方法(0)

调用setRequestedOrientation()以在横向模式下显示时,活动创建两次

我有一个Android应用程序,我想强制平板电脑(sw600dp和更高)以横向模式显示和手机以纵向模式显示,所以我处理我的BaseActivity类的onCreate

boolean isTablet= getResources().getBoolean(R.bool.isTablet);
if (isTablet) {
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else { 
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} 
Run Code Online (Sandbox Code Playgroud)

以及我在bools.xml文件中放入"isTablet"并将其放入的方式

手机的文件夹

   <resources>
        <bool name="isTablet">false</bool>
   </resources>
Run Code Online (Sandbox Code Playgroud)

平板电脑的值 - sw600dp

   <resources>
        <bool name="isTablet">true</bool>
   </resources>
Run Code Online (Sandbox Code Playgroud)

在AndroidManifest中我使用

android:screenOrientation="nosensor"
Run Code Online (Sandbox Code Playgroud)

只需确保禁用设备方向的传感器.

这似乎是我的方法工作正常(平板电脑和手机肖像)但是当我在Nexus 7上运行我的应用程序时问题发生 - 我的活动创建了两次.这些步骤是:

  1. 肖像中的洞Nexus 7(如果我在风景中持有平板电脑就没问题)
  2. 然后运行应用程序

我发现问题是方法setRequestedOrientation()(上面有两个步骤).所以我不想再调用那种方法了.我尝试在AndroidManifest中设置方向,如:

android:screenOrientation="@integer/orientation"
Run Code Online (Sandbox Code Playgroud)

因为:SCREEN_ORIENTATION_LANDSCAPE = 0 SCREEN_ORIENTATION_PORTRAIT = 1

我在integers.xml文件中声明"orientation"并将其放入

手机的文件夹

<resources>
    <integer name="orientation">1</integer>
</resources>
Run Code Online (Sandbox Code Playgroud)

平板电脑的值 - sw600dp

<resources>
    <integer name="orientation">0</integer>
</resources>
Run Code Online (Sandbox Code Playgroud)

再次,我的方法往往工作正常但我发现AndroidMenifest只是理解文件夹中的"方向" ,而不是在values-sw600dp文件夹中.我不希望我的活动打2次.你有这样的问题吗?你能解决吗?谢谢.

android

6
推荐指数
1
解决办法
1867
查看次数

标签 统计

android ×1