简体   繁体   中英

Setting Android Activity screen orientation with values.xml

I am trying to setup activity screen orientation with values from XML file in res/values. I would like to do that because, more or less, I need same Activity for both tablet (landscape) and smartphone (portrait).

First try

Manifest:

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

config.xml:

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

But with this setting application won't appear on device and it will return this error:

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

Second

OK, so I simply changed it to this

Manifest:

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

config.xml:

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

I used 1 because ActivityInfo.SCREEN_ORIENTATION_PORTRAIT == 1.

But this is not working either. It seems that I may modify some values like application / activity name but not screen orientation ?

I know that I may workaround it by code but for some reason it feels that this also should be obtainable by XML values file.

It is somehow possible to achieve it by XML values ?

Same problem for me with your second exlanation and I used a workaround by code which you aren't looking for.

I added 4 values folders under res folder. "values", "values-v11", "values-v14" and "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" .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM