Android 屏幕方向的清单回退

Android 屏幕方向的清单回退,android,Android,在中,有多种不同的方式指定屏幕方向: <integer name="customScreenOrientation">?android:attr/screenOrientation</integer> 景观 sensorscape添加到API 9中 userscape添加到API 18中 如何指定userscape,但在较旧版本的Android上,让它回退到sensorscape,甚至在较旧版本上回退到scape?我在文档中找不到如何做到这一点 我认为没有办法在清单

在中,有多种不同的方式指定
屏幕方向

<integer name="customScreenOrientation">?android:attr/screenOrientation</integer>
  • 景观
  • sensorscape
    添加到API 9中
  • userscape
    添加到API 18中

如何指定
userscape
,但在较旧版本的Android上,让它回退到
sensorscape
,甚至在较旧版本上回退到
scape
?我在文档中找不到如何做到这一点

我认为没有办法在清单本身中实现回退机制

我建议您在清单中指定{userscape,sensorscape,scape}之一。然后,在运行时检查版本并进行即兴创作

比如说,您决定在清单中使用
android:screenOrientation=“userscape”

在活动的
onCreate(Bundle)
中,在设置内容之前:

int sdkInt = Build.VERSION.SDK_INT;

// if we're running on some API level within [9, 18), use `sensorLandscape`
if (sdkInt >= Build.VERSION_CODES.GINGERBREAD /* 9 */ 
        && sdkInt < Build.VERSION_CODES.JELLY_BEAN_MR2 /* 18 */) {
    setRequestedOrientation(
            ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
} else if (sdkInt < Build.VERSION_CODES.GINGERBREAD /* 9 */) {
    setRequestedOrientation(
            ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}

// API 18 or above - handled in manifest

setContentView(R.layout.whatever);
因此,如果要定义一个
整数
,例如:

<!-- `0` for `landscape` -- defined in values/integers.xml -->
<integer name="customScreenOrientation">0</integer>

<!-- `6` for `sensorLandscape` -- defined in values-v9/integers.xml -->
<integer name="customScreenOrientation">6</integer>

<!-- `11` for `userLandscape` -- defined in values-v18/integers.xml -->
<integer name="customScreenOrientation">11</integer>
接下来,创建
values/integers.xml
(一个文件)并定义一个整数
customScreenOrientation

<integer name="customScreenOrientation">?android:attr/screenOrientation</integer>
?android:attr/screenOrientation
您的活动标记将如下所示:

<activity
    ....
    android:theme="@style/AppTheme"
    android:screenOrientation="@integer/customScreenOrientation"/>


与第二种方法相比,这种方法的优点是我们可以使用枚举代替硬编码值。同样,如果枚举值是固定设置的,则这两种方法是等效的。如果他们真的改变了,第二种方法将失败,而第三种方法将继续进行。

这是可行的。我很想看到一个更优雅的解决方案,但可能没有。@Tenfour04我对这个问题进行了更多的研究,并找到了另一个解决方案——我认为它并不优雅,但确实提供了一个代码更少的解决方案。@Tenfour04添加了另一个(我希望最后一个)实现回退机制的方法。我想我还是喜欢第一种方法,因为它紧凑。事实上,我认为清单可能完全可以避免,只要有一个三个条件,否则会在一个位置阻止所有内容。@Tenfour04我同意。第一种方法以及您的更改将是最好的。我正在检查是否有可能只使用xml的解决方案——为了完整性起见,我添加了其他方法。
<activity
    ....
    android:theme="@style/AppTheme"
    android:screenOrientation="@integer/customScreenOrientation"/>