Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to use an xml string value to determine layout orientation

Tags:

android

I have a simple linear layout that I would like to change based on the screen size of the device. What I am trying to do is something like

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="@string/cover_orientation"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>

I have created different dimen.xml files under values and values-xlarge so that the cover_orientation variable will take on a different value (either 'vertical' or 'horizontal') based on the screen size.

string name="cover_orientation">"vertical"

But this doesn't work. I have found a temporary work around that involves checking the screen size and changing the orientation manually:

if(getResources().getString(R.string.screen_size) == "xlarge"){
    ((LinearLayout)convertView).setOrientation(1);
}

but it seems like you should be able to do it the first way (much more elegant/less code).

I considered just having a different layout for each screen size, but the layout is actually quite big and this is the only change I need for the different screen sizes. So it didn't make much sense to me to duplicate the entire layout.

Thanks!

like image 293
odiggity Avatar asked Jun 22 '11 19:06

odiggity


1 Answers

A nice way to do this is to add

android:orientation="@integer/cover_orientation"

on your LinearLayout and defining it like below.

in values/consts.xml:

<resources>

    <integer name="orientation_horizontal">0</integer>
    <integer name="orientation_vertical">1</integer>

</resources>

in values/something.xml:

<resources>

    <integer name="cover_orientation">@integer/orientation_vertical</integer>

</resources>

in values-land/something.xml:

<resources>

    <integer name="cover_orientation">@integer/orientation_horizontal</integer>

</resources>

This way you avoid hardcoding zeros and ones in your orientation variable definitions across the app.

like image 116
MaciejGórski Avatar answered Jan 04 '23 06:01

MaciejGórski