使用values.xml设置Android Activity屏幕方向

5
我将尝试使用res/values中的XML文件设置活动屏幕方向。我这样做的原因是,我需要在平板电脑(横屏)和智能手机(竖屏)上使用相同的Activity。

第一次尝试

清单:

<activity android:name="..." android:screenOrientation="@string/defaultOrientation"/>

config.xml:

<string name="defaultOrientation">portrait</string>

但是使用此设置后,应用程序将不会出现在设备上,并且将返回以下错误:

java.lang.NumberFormatException: Invalid int: "portrait"

第二步

好的,所以我只需要将其更改为以下内容:

清单:

<activity android:name="..." android:screenOrientation="@integer/defaultOrientation"/>

config.xml:

<integer name="defaultOrientation">1</integer>

我使用了1,是因为ActivityInfo.SCREEN_ORIENTATION_PORTRAIT等于1。

但这个方法也没有起作用。似乎我可以修改一些值,比如应用程序/活动名称,但不能修改屏幕方向?

我知道我可以通过代码解决这个问题,但出于某种原因,我觉得这也可以通过XML值文件获得。

是否可以通过XML值来实现?


1
你的答案对我非常有效。android:screenOrientation="@integer/defaultOrientation" 就可以了。 - user123321
1个回答

4

我和你第二个解释遇到了相同的问题,并使用了代码的变通方法,您没有寻找。

我在res文件夹下添加了4个values文件夹。 "values",“values-v11”,“values-v14”和“values-sw720dp”。

All values folders have "integers.xml".

"values" and "values-v14" have value 1 which is portrait orientation;
<integer name="portrait_if_not_tablet">1</integer>.

"values-v11" and "values-sw720dp" have value 2 which is user orientation;
<integer name="portrait_if_not_tablet">2</integer>.

And in Manifest file, activity has a property like;
android:screenOrientation="@integer/portrait_if_not_tablet".

All "values", "values-v11", "values-v14" are working as expected but "values-sw720dp"!

While debugging I realized that value of portrait_if_not_tablet comes as expected on a sw720dp device(with API 16) with getResources().getInteger(R.integer.portrait_if_not_tablet) but when i checked the value of current orientation by getRequestedOrientation() I got a different value.

int requestedOrientation = getResources().getInteger(R.integer.portrait_if_not_tablet);
int currentOrientation = getRequestedOrientation();
if (currentOrientation != requestedOrientation) {
    setRequestedOrientation(requestedOrientation);
}

So I used a code block on onCreate method of my activities to solve this.


添加一个名为_values-sw720dp-v14_的新文件夹,其中包含包含'<integer name="portrait_if_not_tablet">2</integer>'的integers.xml没有改变任何东西。 - Devrim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接