Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Android Activity screen orientation with values.xml

Tags:

java

android

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 ?

like image 494
outlying Avatar asked Oct 05 '22 19:10

outlying


1 Answers

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".

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.

like image 107
Devrim Avatar answered Oct 10 '22 02:10

Devrim